Loading

剑指 Offer 12. 矩阵中的路径

思路

dfs +剪枝

 

代码实现

 1 class Solution {
 2 private:
 3     int d[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
 4     int m, n;   //n行m列
 5     bool vis[210][210] = {false};
 6     
 7 public:
 8     bool exist(vector<vector<char>>& board, string word) {
 9         n = board.size();
10         m = board[0].size();
11         
12         for(int i = 0; i < n; ++i) {
13             for(int j = 0; j < m; ++j) {
14                 //memset(vis, false, sizeof(vis));
15                 //vector<vector<bool>> vis(n, vector<bool>(m, false)); //使用vector会超时,不知道为啥
16                 if(dfs(board, word, i, j, 0))
17                     return true;
18             }
19         }
20         return false;
21     }
22 
23     //当前搜索第index个字符
24     bool dfs(vector<vector<char>>& board, string targetWord, int x, int y, int index) {
25         
26         //剪枝
27         if(board[x][y] != targetWord[index])
28             return false;
29         
30         //剪枝
31         if(index == targetWord.length()-1)
32             return true;
33 
34         vis[x][y] = true;
35 
36         for(int i = 0; i < 4; ++i) {
37             int xx = x + d[i][0];
38             int yy = y + d[i][1];
39             if(xx < 0 || yy < 0 || xx >= n || yy >= m || vis[xx][yy]) 
40                 continue;
41        //找到一个答案递归即可返回,不用继续往后找其他答案
42             if(dfs(board, targetWord, xx, yy, index+1))
43                 return true;
44             
45         }
46 
47         vis[x][y] = false;  //记得回溯
48         return false;
49     }
50 };

 

复杂度分析

 

 

参考

面试题12. 矩阵中的路径(深度优先搜索 DFS ,清晰图解)

posted @ 2020-10-21 17:45  拾月凄辰  阅读(77)  评论(0编辑  收藏  举报