链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
类似使用这个技巧的问题还有:「力扣」第 130 题:被围绕的区域、「力扣」第 200 题:岛屿数量。
class Solution {
public:
vector<vector<int>> direction{{0, 1},{0,-1},{1,0},{-1,0}};
bool exist(vector<vector<char>>& board, string word) {
if(board.size() == 0) {
return false;
}
int row = board.size();
int col = board[0].size();
// 记录状态,回溯使用
vector<vector<bool>> visited(row, vector<bool>(col, false));
for(int i = 0; i < row; ++i) {
for(int j = 0; j < col; ++j) {
// 从第(i,j)坐标为止开始搜索
if(dfs(board, row, col, 0, i, j, word, visited)) {
return true;
}
}
}
return false;
}
bool dfs(const vector<vector<char>>& board, int row, int col, int begin, int x, int y,
const std::string& word, vector<vector<bool>>& visited) {
// 遍历到字符串末尾
if(begin == word.size()-1) {
// 判断字符串末尾是否相等
return board[x][y] == word[begin];
}
// 如果不想等,返回false
if(board[x][y] != word[begin]) {
return false;
}
// 记录这个节点已经访问过
visited[x][y] = true;
// 遍历四个方向,继续查找
for(int i = 0; i < direction.size(); ++i) {
int new_x = x + direction[i][0];
int new_y = y + direction[i][1];
if(new_x >= 0 && new_x < row && new_y >= 0 && new_y < col && !visited[new_x][new_y]) {
if(dfs(board, row, col, begin+1, new_x, new_y, word, visited)) {
return true;
}
}
}
// 回溯
visited[x][y] = false;
return false;
}
};
class Solution {
public:
std::vector<std::vector<int>> direction{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
if (m <= 0) {
return false;
}
int n = board[0].size();
if (n <= 0) {
return false;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == word[0]) {
int begin = 1;
std::vector<std::vector<bool>> visited(m, std::vector<bool>(n ,false));
visited[i][j] = true;
if (dfs(begin, i, j, m, n, board, word, visited)) {
return true;
}
}
}
}
return false;
}
private:
bool dfs(int begin, int row, int col, int m, int n, vector<vector<char>>& board, std::string& word, std::vector<std::vector<bool>>& visited) {
if (begin >= word.size()) {
return true;
}
for (auto& direc : direction) {
int next_row = row + direc[0];
int next_col = col + direc[1];
if (next_row < 0 || next_row >= m || next_col < 0 || next_col >= n
|| board[next_row][next_col] != word[begin]
|| visited[next_row][next_col]) {
continue;
}
visited[next_row][next_col] = true;
if (dfs(begin+1, next_row, next_col, m, n, board, word, visited)) {
return true;
}
visited[next_row][next_col] = false;
}
return false;
}
};