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
.
Difficulty: Medium
又是一道回溯,注意下各种陷阱吧。。。wa了好多次
bool gen(vector<vector<char> >& board,vector<vector<int> >& v,string word,int index,int dep,int row,int col){
if(dep==0||index>=word.length())
return true;
for(int i = col-1;i<=col+1;i++)
for(int j = row-1;j<=row+1;j++)
{
if(i>=0&&j>=0&&i<board[0].size()&&j<board.size()&&(i==col||j==row)){
if(v[j][i]==0&&board[j][i]==word[index])
{
if(dep==1)
return true;
v[j][i]=1;
if(gen(board,v,word,index+1,dep-1,j,i))
return true;
v[j][i]=0;
}
}
}
return false;
}
bool exist(vector<vector<char> >& board, string word) {
int m = board[0].size();
int n = board.size();
int len = word.length();
if(m==0||n==0||len==0||m*n<len)
return false;
vector<vector<int> >v (n,vector<int>(m,0));
for(int i = 0;i<m;i++)
for(int j = 0;j<n;j++)
{
if(board[j][i]==word[0]){
v[j][i]=1;
if(gen(board,v,word,1,len-1,j,i))
return true;
v[j][i]=0;
}
}
return false;
}