LeetCode79:单词搜索

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

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

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

深度优先搜索,用一个visited数组记录哪些位置被访问过。

 1 class Solution {
 2 public:
 3       int dir[4][4]={{-1,0},{1,0},{0,-1},{0,1}};
 4     
 5     bool exist(vector<vector<char>>& board, string word) {
 6         int m=board.size();
 7         int n=board[0].size();
 8         vector<vector<bool>> visited(m,vector<bool>(n));
 9         
10         
11         for(int i=0;i<m;i++){
12             for(int j=0;j<n;j++){
13                 if(dfs(i,j,0,board,word,visited))
14                     return true;
15             }
16         }
17         return false;
18     }
19     
20     bool dfs(int x,int y,int index,vector<vector<char>>& board,string &word,vector<vector<bool>>& visited){
21         if(index==word.size()-1){
22             return word[index]==board[x][y];
23         }
24         
25         if(word[index]!=board[x][y])
26             return false;
27             visited[x][y]=true;
28             for(int i=0;i<4;i++){
29                 int new_x=x+dir[i][0];
30                 int new_y=y+dir[i][1];
31                 
32                 if(new_x>=0&&new_x<board.size()&&new_y>=0&&new_y<board[0].size()&&!visited[new_x][new_y])
33                     if(dfs(new_x,new_y,index+1,board,word,visited))
34                         return true;
35             }
36             visited[x][y]=false;
37             
38         
39         return false;
40     }
41 };
原文地址:https://www.cnblogs.com/rookiez/p/13218266.html