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
| class Solution { public: int flag[205][205]; bool ans = false; void dfs(vector<vector<char>>& board,int x,int y,string& word,int pos) { if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] != word[pos] || flag[x][y] ==1 || ans == true) return; if(flag[x][y] == 0) { if(pos == word.size() - 1) { ans = true; return; } flag[x][y] = 1; dfs(board,x+1,y,word,pos+1); dfs(board,x-1,y,word,pos+1); dfs(board,x,y+1,word,pos+1); dfs(board,x,y-1,word,pos+1); flag[x][y] = 0; } } bool exist(vector<vector<char>>& board, string word) { for(int i = 0 ; i < board.size() ; i++) for(int j = 0; j < board[0].size() ; j++) dfs(board,i,j,word,0); return ans; } };
|