# LeetCode 79. 单词搜索

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3

 1 class Solution {
2 public:
3     bool dfs(vector<vector<char>>& board,string& word,int index,int x,int y){
4         if(index==word.length()) return true;
5         if(board[x][y]!=word[index]) return false;
6         char tmp=board[x][y];
7         board[x][y]='.';
8         if(x>0&&dfs(board,word,index+1,x-1,y)) return true;
9         if(x<board.size()-1&&dfs(board,word,index+1,x+1,y)) return true;
10         if(y>0&&dfs(board,word,index+1,x,y-1)) return true;
11         if(y<board[0].size()-1&&dfs(board,word,index+1,x,y+1)) return true;
12         board[x][y]=tmp;
13         return false;
14     }
15     bool exist(vector<vector<char>>& board, string word) {
16         if(board.size()==0) return false;
17         if(board.size()==1&&board.size()==1&&word.length()==1) return board[0][0]==word[0];
18         for(int i=0;i<board.size();i++){
19             for(int j=0;j<board[0].size();j++){
20                 if(dfs(board,word,0,i,j)) return true;
21             }
22         }
23         return false;
24     }
25 };

posted @ 2020-04-11 21:01  午夜的行人  阅读(32)  评论(0编辑  收藏
Live2D