题目:
关于DFS的一般写法,要注意的是:
- 置vis要放在for的外面,而不是在for的里面
- 用数组作为vis的速度会远远快于用set作为vis的速度
- 可以将下面的这一份代码作为dfs的一般模板
class Solution {
public:
int vis[20][20];
// string now = "";
int flag = 0;
void dfs(vector<vector<char>>& board, string word, int x, int y, string& now) {
if(now.length() > word.length() + 1) return ;
int dir[][2] = {
{1,0}, // 下
{-1,0}, // 上
{0,1}, // 右
{0,-1} // 左
};
vis[x][y] = 1;
if(now == word) {
flag = 1;
}
for(int i = 0;i < 4; i ++) {
int now_x = x + dir[i][0];
int now_y = y + dir[i][1];
if(now_x >= 0 && now_x < board.size()) {
if(now_y >= 0 && now_y < board[0].size()) {
if(vis[now_x][now_y] == 0) {
string temp = now;
if(board[now_x][now_y] != word[now.length()]) continue;
now += board[now_x][now_y];
dfs(board, word, now_x, now_y, now);
now = temp;
}
}
}
}
vis[x][y] = 0;
}
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 ++) {
string now = "";
now = board[i][j];
dfs(board, word, i, j, now);
if(flag == 1) return true;
}
}
if(flag == 1) return true;
return false;
}
};