image.png
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(word.empty() || word.length() == 0){
return true;
}
if(board.size() == 0 || board[0].size() == 0) return false;
vector<vector<bool>> used(board.size(), vector<bool>(board[0].size(), false));
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size(); j++){
if(dfs(board, used, word, 0, i, j))
return true;
}
}
return false;
}
private:
bool dfs(vector<vector<char>> board, vector<vector<bool>> &used,string word, int cur, int x, int y){
if(cur == word.length()){
return true;
}
if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || used[x][y] || word[cur] != board[x][y]) return false;
used[x][y] = true;
bool res = dfs(board, used, word, cur + 1, x+1, y) ||
dfs(board, used, word, cur + 1, x, y + 1) ||
dfs(board, used, word, cur + 1, x-1, y) ||
dfs(board, used, word, cur + 1, x, y - 1);
used[x][y] = false;
return res;
}
};
网友评论