码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer---矩阵中的路径

时间:2018-10-25 22:43:10      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:div   path   int   public   ++   ||   www   ranking   class   

题目:矩阵中的路径

要求:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下  移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

1 class Solution {
2 public:
3     bool hasPath(char* matrix, int rows, int cols, char* str)
4     {
5     
6     }
7 };

解题代码:

 1 class Solution {
 2 public:
 3     bool hasPath(char* matrix, int rows, int cols, char* str) {
 4         if(matrix == nullptr || rows < 1 || cols < 1 || str == nullptr)
 5             return false;
 6 
 7         bool *visited = new bool[rows * cols];
 8         memset(visited, 0, rows * cols);
 9 
10         int pathLength = 0;
11         for(int row = 0; row < rows; row++){
12             for(int col = 0; col < cols; col++){
13                 if(hasPathCore(matrix, rows, cols, row, col, str, pathLength, visited))
14                     return true;
15             }
16         }
17         delete[] visited;
18         return false;
19     }
20 private:
21     bool hasPathCore(char* matrix, int rows, int cols, int row, int col,
22         char* str, int &pathLength, bool* visited){
23         // 到达字符串末尾
24         if(str[pathLength] == \0)
25             return true;
26 
27         bool hasPath = false;
28         if(row >= 0 && col >= 0 && row < rows && col < cols
29             && matrix[row * cols + col]==str[pathLength] && !visited[row * cols + col]){
30             pathLength++;
31             visited[row * cols + col] = true;
32 
33             // 若4个相邻格子中有一个方向的元素和要寻找的元素相同,则hasPath=true
34             hasPath = hasPathCore(matrix, rows, cols, row + 1, col, str, pathLength, visited)
35                         || hasPathCore(matrix, rows, cols, row - 1, col, str, pathLength, visited)
36                         || hasPathCore(matrix, rows, cols, row, col + 1, str, pathLength, visited)
37                         || hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, visited);
38 
39             // 如果4个相邻的格子都没有匹配字符串中下标为pathLength+1的字符,则表明定位错误,
40             // 需要回到前一个字符pathLength-1,重新定位
41             if(!hasPath){
42                 pathLength--;
43                 visited[row * cols + col] = false;
44             }
45         }
46         return hasPath;
47     }
48 };

 

剑指offer---矩阵中的路径

标签:div   path   int   public   ++   ||   www   ranking   class   

原文地址:https://www.cnblogs.com/iwangzhengchao/p/9853315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!