题目:
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
.分析:此题有点像深度优先搜索。
代码如下:
bool searchword(vector<vector<char> > board,string word,int i, int j,int currentindex)
{
board[i][j]='0';
if(currentindex==word.length())return true;
if(i>0)
{
if(board[i-1][j]==word[currentindex])
{
if(searchword(board,word,i-1,j,currentindex+1))
return true;
}
}
if(i<board.size()-1)
{
if(board[i+1][j]==word[currentindex])
{
if(searchword(board,word,i+1,j,currentindex+1))
return true;
}
}
if(j>0)
{
if(board[i][j-1]==word[currentindex])
{
if(searchword(board,word,i,j-1,currentindex+1))
return true;
}
}
if(j<board[0].size()-1)
{
if(board[i][j+1]==word[currentindex])
{
if(searchword(board,word,i,j+1,currentindex+1))
return true;
}
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
int n=word.length();
if(n==0)return true;
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[i].size();j++)
{
if(board[i][j]==word[0])
{
if(searchword(board,word,i,j,1))
return true;
}
}
}
return false;
}