一种是K神的做法,由于大家都抄作业,啊哈算法形式的深度优先很难找到,这里记录一下
解法 DFS 1.0
class Solution {
public:
int rows;
int cols;
bool exist(vector<vector<char>>& board, string word) {
if(word.empty() || board.empty())
return word.empty();//字符串为空返回正确,字符串不空矩阵空返回错误
rows = board.size()-1;
cols = board[0].size()-1;
for(int i = 0; i < board.size(); i ++)
for(int j = 0; j < board[0].size(); j ++)
if(board[i][j] == word [0])
if(dfs(board, word, i, j, 0)) return true;
return false;
}
bool dfs(vector<vector<char>>& board, string& word, int i, int j, int dis) {
if(i > rows || i < 0 || j > cols || j < 0|| board[i][j] != word[dis])
return false;
if(dis == word.size() - 1)
return true;
char tmp = board[i][j];
board[i][j]='\0';
//四个方向有一个正确就说明当前点正确;
bool cur = dfs(board, word, i + 1, j, dis + 1) || dfs(board, word, i - 1, j, dis + 1) || dfs(board, word, i, j + 1, dis + 1) || dfs(board, word, i, j - 1, dis + 1);
board[i][j]=tmp;
return cur;
}
};
解法 DFS 1.1
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
vector<vector<int>>vis(m, vector<int>(n, 0));
for(int i = 0; i < m; i ++){
for(int j = 0; j < n; j ++){
if(board[i][j] == word[0]){
if(dfs(board, vis, i, j, word, 1)) return true;
}
}
}
return false;
}
vector<vector<int>> dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
//其中 vis 数组用于标识进入过的格子, idx 表示要找的下一个坐标, 也就是 word 的前 idx 个字母已经找到了
bool dfs(vector<vector<char>>& board, vector<vector<int>>&vis, int i, int j, string& word, int idx){
//标识 (i, j) 位置被寻找过了
if(idx == word.size()) return true;
//向四个方向寻找
for(auto xy : dir){
int x = i + xy[0], y = j + xy[1];
//如果不满足条件, 换其他方向寻找
if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || vis[x][y] || board[x][y] != word[idx]) continue;
else{
vis[i][j] = 1;
//满足条件, 继续深搜
if(dfs(board, vis, x, y, word, idx+1)) return true;
}
}
//回溯
vis[i][j] = 0;
return false;
}
};
两种方法逻辑其实是一样的,而第一种代码更加简洁好看,第二种的模板适应性更广。
考虑到第二种办法的标记数组是没有必要的,改进出第三种办法
DFS 2.0
class Solution {
public:
vector<vector<int>>next={{0,1},{1,0},{0,-1},{-1,0}};
int rows;
int cols;
bool exist(vector<vector<char>>& board, string word) {
if(word.empty() || board.empty())
return word.empty();//字符串为空返回正确,字符串不空矩阵空返回错误
rows = board.size()-1;
cols = board[0].size()-1;
for(int i = 0; i < board.size(); i ++)
for(int j = 0; j < board[0].size(); j ++)
if(board[i][j] == word [0])
if(dfs(board, word, i, j, 0)) return true;
return false;
}
bool dfs(vector<vector<char>>& board, string& word, int i, int j, int dis) {
char temp = board[i][j];
board[i][j]='\0';
dis++;
if(dis == word.size())
return true;
for( int k = 0; k <= 3; k ++) {
int ti = i + next[k][0];
int tj = j + next[k][1];
if(ti > rows || ti < 0 || tj > cols || tj < 0|| board[ti][tj] != word[dis]) continue;
if(dfs(board, word, ti, tj, dis)) return true;
}
board[i][j] = temp;
return false;
}
};
PS:如果用后面两种办法的时候注意一个地方
如果遇到这样的样例:
[[“a”]]
“a”
这时候word.size()为1;不提前dis++,而采取word[dis+1]会导致数组越界。
为了避免这种情况,dis一开始就从1开始判断。