# 【每日打卡】Day21：单词搜索 C++实现

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

class Solution {
public:
bool flag = false;
int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};
int rs = 0, cs = 0;
//建立一个map，用于标记访问与否
map<int,bool> vis;
void dfs(vector<vector<char>>& board, string word, int x, int y, int k){
if(board[x][y] == word[k]){
// 这里判断flag十分必要  只要找到一种方案即可   如果不限定flag 会一直找所有方案
if(k == word.length()-1 || flag){
flag = true;
return;
}
else{
for(int i = 0; i < 4; i ++){
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= rs || ny >= cs || vis[nx*cs+ny])
continue;
vis[nx*cs+ny] = true;
dfs(board,word,nx,ny,k+1);
vis[nx*cs+ny] = false;
}
}
}
return;
}

bool exist(vector<vector<char>>& board, string word) {
if(board.size() == 0 || word.size() == 0)
return false;
rs = board.size(), cs = board[0].size();
for(int i = 0; i < rs; i ++){
for(int j = 0; j < cs; j ++){
if(board[i][j] == word[0]){
vis[i*cs+j] = true;
dfs(board,word,i,j,0);
vis[i*cs+j] = false;
if(flag)    return flag;
}

}
}

return flag;

}

};