您的位置:首页 > 其它

leetcode || 79、Word Search

2015-04-10 11:19 337 查看
problem:

Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring.

The same letter cell may not be used more than once.
For example,

Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]

word =
"ABCCED"
, -> returns
true
,

word =
"SEE"
, -> returns
true
,

word =
"ABCB"
, -> returns
false
.

Hide Tags
Array Backtracking

题意:在一个字符矩阵中搜索一个字,每个字符只能使用一次,搜索方向为上下左右

thinking:

(1)确定方法:全局搜索满足条件的解,使用DFS

(2)深搜成功的条件是:深搜成功一次,步数+1,直到深搜的步数达到word的长度

(3)新开一个矩阵大小的二维数组,记录矩阵的字符是否用过,先在矩阵中搜索word[0]的位置,一次为起点开始深搜,每次搜索上下左右四个方向

code:

class Solution {
private:
bool flag;
public:
bool exist(vector<vector<char> > &board, string word) {
int m=board.size();
int n=board[0].size();
int Maxdep=word.size();
flag = false;
vector<int> a1(n,0);
vector<vector<int> > array(m,a1);
for(int i=0;i<m;i++) //寻找搜索起点
{
for(int j=0;j<n;j++)
{
if(flag) //加快搜索
return true;
if(board[i][j]==word[0])
dfs(0,Maxdep,i,j,array,board,word);
}
}
return flag;
}
protected:
void dfs(int dep,int Maxdep,int x, int y,vector<vector<int> > &array,
vector<vector<char> > &board, string word)
{
if(flag)  //不能去掉,去掉就超时了
return;
int m=board.size();
int n=board[0].size();
if(dep==Maxdep) //这个必须放在x,y 边界判断的前面
{
flag=true;
return ;
}
if(x<0 || x>=m || y<0 || y>=n)
return;
if(array[x][y]==1)
return;
if(board[x][y]==word[dep]) //四个方向深搜
{
array[x][y]=1;
dfs(dep+1,Maxdep,x-1,y,array,board,word);
dfs(dep+1,Maxdep,x,y-1,array,board,word);
dfs(dep+1,Maxdep,x+1,y,array,board,word);
dfs(dep+1,Maxdep,x,y+1,array,board,word);
array[x][y]=0;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: