地址
https://leetcode-cn.com/problems/word-search/submissions/
描述
思想
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
//枚举起点
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
if(dfs(board,word,0,i,j)) return true;
}
}
//起点枚举完,都没实现,就return false
return false;
}
int dx[4]={
-1,0,1,0},dy[4]={
0,1,0,-1};
bool dfs(vector<vector<char>>& board,string &word,int u,int x,int y ){
if(board[x][y]!=word[u]) return false;
if(u==word.size()-1) return true;
//不能往回走,怎么实现
//我们把走过的路变为'.',这个在board中不会出现的字符,这样就不会走回头路
char t=board[x][y];
board[x][y]='.';
for(int i=0;i<4;i++){
int a=x+dx[i],b=y+dy[i];
if(a<0||a>=board.size()||b<0||b>=board[0].size()||board[a][b]=='.') continue;
if(dfs(board,word,u+1,a,b)) return true;
}
//回溯
board[x][y]=t;
return false;
}
};