1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Solution { public:
int dirx[4] = {0, 1, 0, -1}; int diry[4] = {-1, 0, 1, 0};
vector<vector<bool>> visit = vector<vector<bool>>(200, vector<bool>(200));
bool dfs(vector<vector<char>>& board, string& word, int count, int i, int j){
if(count == word.size()) return true; for(int k = 0; k < 4; k++){
int x = j + dirx[k]; int y = i + diry[k];
if(x >= 0 && x < board[0].size() && y >= 0 && y < board.size()){
if(board[y][x] == word[count] && !visit[y][x]){
visit[y][x] = true;
if(dfs(board, word, count + 1, y, x)) return true;
visit[y][x] = false; } } }
return false; }
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[i].size(); j++){
if(board[i][j] == word[0]){
visit[i][j] = true; if(dfs(board, word, 1, i, j)) return true; visit[i][j] = false; } } }
return false; } };
|