79. 单词搜索
思路:回溯
上下左右挨个找一遍
但是在写代码过程中遇到了一些问题非常烦。
处理过程中边界总是划分不清
另外回溯过程中尽量先写不成立的,然后return回去,不然太难搞了
class Solution {
public:
bool dfs(int x, int y, int index, vector<vector<char>>& board,string& word, vector<vector<bool>>& visited) {
if (board[x][y] == word[index]&& visited[x][y]==0) {
visited[x][y] = 1;
//当前的符合要找的
if (index == word.size() - 1) {
visited[x][y] = 0;
return true;
}
//向上
if (x - 1 >= 0 && dfs(x - 1, y, index + 1, board, word, visited)) {
visited[x][y] = 0;
return true;
}
//向下
if (x + 1 < board.size() && dfs(x + 1, y, index + 1, board, word, visited)) {
visited[x][y] = 0;
return true;
}
//向左
if (y - 1 >= 0 && dfs(x, y - 1, index + 1, board, word, visited)) {
visited[x][y] = 0;
return true;
}
//向右
if (y + 1 < board[0].size() && dfs(x, y + 1, index + 1, board, word, visited)) {
visited[x][y] = 0;
return true;
}
visited[x][y] = 0;
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty()) {
return false;
}
if (word.empty()) {
return true;
}
int m = board.size();
int n = board[0].size();
vector<vector<bool>> visited(m, vector<bool>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(i, j, 0, board, word,visited)) {
return true;
}
}
}
return false;
}
};