※剑指offer系列54:矩阵中的路径

这个题目用的是回溯法。

之前回溯法练得比较少,所以这个题还是需要重视。

回溯法是算法里学过的,就是从第一个可能得路径开始找,一直找到最后一个。

这个题目要注意一下几点:

1.从第一个开始找,如果第一个元素等于要寻找的字符串的第一个元素,就继续去寻找该元素的上下左右,看是否等于其下一个。一直匹配到最后一个元素。

2.如果这个元素的下一个在它的上下左右都找不到,就返回上一层,说明该元素也许走错了。

3.因为访问过得路径不能再次访问,因此要建立一个同样大小的bool型的变量记录该当前位置是否已经走过。

 1 class Solution {
 2 public:
 3     bool hasPath(char* matrix, int rows, int cols, char* str)
 4     {
 5         if (matrix == NULL || rows <= 0 || cols <= 0 || str == NULL)
 6             return false;
 7 
 8         bool* visited = new bool[rows*cols];//定义一个跟矩阵同样大小的变量,记录每个位置是否被访问过
 9         memset(visited, 0, rows*cols);
10 
11         int index = 0;
12         for(int i=0;i<rows;i++)
13             for (int j = 0; j < cols; j++)
14             {
15                 if (hasPathcore(matrix, rows, cols, i, j,str, index, visited))
16                     return true;
17             }
18         delete[]visited;
19         return false;
20     }
21     bool hasPathcore(char* matrix, int rows, int cols, int row,int col,char* str,int index,bool *visit)
22     {
23         if (str[index] == '')//递归终止条件,一直寻找到了结尾
24             return true;
25         bool has=false;
26         if (row <= rows&&col <= cols&&matrix[row*cols + col] == str[index] && !visit[row*cols + col])
27         {
28             visit[row*cols + col] = true;
29             index++;
30             //寻找字符串中剩下的
31             has = hasPathcore(matrix, rows, cols, row, col+1, str, index, visit)//
32                 || hasPathcore(matrix, rows, cols, row+1, col, str, index, visit)//
33                 || hasPathcore(matrix, rows, cols, row, col-1, str, index, visit)//
34                 || hasPathcore(matrix, rows, cols, row-1, col, str, index, visit);//
35 
36             if (!has)//上下左右都没找到下一个元素,说明该元素走错了,退回上一步
37             {
38                 index--;
39                 visit[row*cols + col] = false;
40             }
41         }
42     
43         return has;
44     }
45 
46 
47 };
原文地址:https://www.cnblogs.com/neverland0718/p/11268411.html