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.
思路
DFS
代码
bool dfs(vector<vector<char>>& board, string word,int x,int y,int level,vector<vector<bool> >&visited) {
if(x<0||x>=board.size()||y<0||y>=board[0].size())return false;
if(visited[x][y])return false;
if(word[level]!=board[x][y])return false;
if(level==word.size()-1)return true;
visited[x][y]=true;
bool flag= dfs(board,word,x+1,y,level+1,visited)
||dfs(board,word,x,y+1,level+1,visited)
||dfs(board,word,x-1,y,level+1,visited)
||dfs(board,word,x,y-1,level+1,visited);
visited[x][y]=false;
return flag;
}
bool exist(vector<vector<char>>& board, string word) {
int m=board.size();
int n=board[0].size();
vector<vector<bool> >visited(m,vector<bool>(n,0));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(dfs(board,word,i,j,0,visited))return true;
}
return false;
}