剑指offer 矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
 
基本思想:
0.根据给定数组,初始化一个标志位数组,初始化为false,表示未走过,true表示已经走过,不能走第二次
1.根据行数和列数,遍历数组,先找到一个与str字符串的第一个元素相匹配的矩阵元素,进入hasPathCore
2.根据i和j先确定一维数组的位置,因为给定的matrix是一个一维数组
3.确定递归终止条件:待判定的字符串str的索引已经判断到了最后一位,此时说明是匹配成功的
4.下面就是本题的精髓,递归不断地寻找周围四个格子是否符合条件,只要有一个格子符合条件,就继续再找这个符合条件的格子的四周是否存在符合条件的格子,直到到达末尾或者不满足递归条件就停止。
5.走到这一步,说明本次是不成功的,我们要还原一下标志位数组index处的标志位,进入下一轮的判断。
 
 1 class Solution {
 2 public:
 3     bool hasPath(char* matrix, int rows, int cols, char* str) {
 4         if (matrix == nullptr || rows <= 0 || cols <= 0 || str == nullptr) {
 5             return false;
 6         }
 7         bool *visited = new bool[rows * cols];
 8         memset(visited, false, rows * cols);
 9         int pathLength = 0;
10         for (int i = 0; i < rows; i++) {
11             for (int j = 0; j < cols; j++) {
12                 if (hasPathCore(matrix, rows, cols, i, j, str, visited, pathLength)) {
13                     return true;
14                 }
15             }
16         }
17         delete[] visited;
18         return false;
19     }
20 private:
21     bool hasPathCore(char* matrix, int rows, int cols, int i, int j, char* str, bool* visited, int pathLength) {
22         if (str[pathLength] == '\0') {
23             return true;
24         }
25         bool hasPath = false;
26         int index = i * cols + j;
27         if (i >= 0 && i < rows
28             && j >= 0 && j < cols
29             && matrix[index] == str[pathLength] 
30             && !visited[index]) {
31             ++pathLength;
32             visited[index] = true;
33             hasPath = hasPathCore(matrix, rows, cols, i - 1, j, str, visited, pathLength)
34                    || hasPathCore(matrix, rows, cols, i + 1, j, str, visited, pathLength)
35                    || hasPathCore(matrix, rows, cols, i, j - 1, str, visited, pathLength)
36                    || hasPathCore(matrix, rows, cols, i, j + 1, str, visited, pathLength);
37             if (!hasPath) {
38                 --pathLength;
39                 visited[index] = false;
40             }
41         }
42         return hasPath;
43     }
44 
45 };

 

posted @ 2019-07-24 16:16  琴影  阅读(463)  评论(0编辑  收藏  举报