简介
回溯
code
class Solution {
public:
int n;
int m;
bool find;
void dfs(vector<vector<char>>& board, vector<vector<bool>>& visited, string &word, int index, int i, int j){
if(index == word.size()){
find = true;
return;
}
if(i >= n) return;
if(i < 0) return;
if(j >= m) return;
if(j < 0) return;
if(board[i][j] == word[index]){
if(visited[i][j] == false) {
visited[i][j] = true;
dfs(board, visited, word, index+1, i, j+1);
visited[i][j] = false;
visited[i][j] = true;
dfs(board, visited, word, index+1, i, j-1);
visited[i][j] = false;
visited[i][j] = true;
dfs(board, visited, word, index+1, i+1, j);
visited[i][j] = false;
visited[i][j] = true;
dfs(board, visited, word, index+1, i-1, j);
visited[i][j] = false;
}
}else{
return;
}
}
bool exist(vector<vector<char>>& board, string word) {
n = board.size();
m = board[0].size();
int index = 0;
vector<vector<bool>> visited(n, vector<bool>(m, false));
find = false;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
dfs(board, visited, word, 0, i, j);
if(find) return true;
}
}
return false;
}
};
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》