原题
思路
这个题主要是DFS,注意边界判断
代码
class Solution {
public:
int xIndex[4] = {-1, 0, 0, 1};
int yIndex[4] = {0, -1, 1, 0};
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
vector<vector<bool>> visit(m, vector<bool> (n));
for (int i = 0; i < m; i++) {
for(int j = 0; j < n; j++){
bool ans = dfs(visit, board, word, 0, i, j);
if (ans) return true;
}
}
return false;
}
bool dfs(vector<vector<bool>>& visit, vector<vector<char>>& board, string word, int nowIndex, int x, int y){
if (board[x][y] != word[nowIndex]) return false;
else if (nowIndex == word.length()-1) {
return true;
}
visit[x][y] = true;
bool result = false;
for (int i = 0; i < 4; i++){
if(x+xIndex[i] >= 0 && x+xIndex[i] < board.size() && y+yIndex[i] >=0 && y+yIndex[i] < board[0].size()) {
if(!visit[x+xIndex[i]][y+yIndex[i]] ) {
bool flag = dfs(visit, board, word, nowIndex+1, x+xIndex[i], y+yIndex[i]);
if (flag) {
result = true;
break;
}
}
}
}
visit[x][y] = false;
return result;
}
};
运行截图
收获
- DFS题一定要注意边界条件和判断条件
- 判断条件一般放进dfs函数里,第一个判断最好也放进去
- dfs一般的模板:
bool dfs(参数) {
if 不满足条件 : return false;
else if 满足: return true;
visited[i]=true;
bool result=dfs(next);
visited[i]=false;
return result;
}
- 二维动态数组可以这样初始化:
vector<vector<int>> visited(m, vector<int> (n));
- 方向可以用pair这么写:
vector<pair<int, int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
使用的时候:
for (auto dir:directions ) {
newi = i + dir.first; newj = j + dir.second;
}