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
| class Solution { public: bool ans = false; int direct[4][2]={ {1,0},{0,1},{-1,0},{0,-1} }; bool book[200][200]={false}; void dfs(const string& word,const vector<vector<char>>& target,int index,int x,int y){ if(ans)return; if(index+1==word.size()){ans=true;return;} for(int i=0;i<4;i++){ int tx= x+direct[i][0],ty = y+direct[i][1]; if(tx<0||tx>=target.size()||ty<0||ty>=target[0].size())continue; if(!book[tx][ty]&&target[tx][ty]==word[index+1]){ book[tx][ty]=true; dfs(word,target,index+1,tx,ty); book[tx][ty]=false; } } } 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){ if(board[i][j]==word[0]){ book[i][j]=true;dfs(word,board,0,i,j);book[i][j]=false; } } } return ans; } };
|