思路:
这道题是典型的迷宫dfs题,通过循环遍历每一个节点,看是否能完成题意即可,具体应该看看代码好好学习一下dfs套路。
代码:
class Solution {
public:
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
bool exist(vector<vector<char>>& board, string word) {
int n = board.size();
int m = board[0].size();
vector< vector<bool> > q(n,vector<bool>(m));
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
if(dfs(i,j,0,board,word,q))
return true;
}
}
return false;
}
bool dfs(int x,int y,int step,vector<vector<char>>& board,string& word,vector< vector<bool> >& q){
if(word[step]==board[x][y]){
q[x][y] = true;
if(step==word.size()-1) return true;
for(int i=0;i<4;++i){
int tx = x+dx[i];
int ty = y+dy[i];
if(tx<0 || tx>=board.size() || ty<0 || ty>=board[0].size()) continue;
if(q[tx][ty]) continue;
if(dfs(tx,ty,step+1,board,word,q))
return true;
}
q[x][y] = false;
}
return false;
}
};