zoukankan      html  css  js  c++  java
  • 剑指offer---矩阵中的路径

    题目:矩阵中的路径

    要求:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下  移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 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] == '')
    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 };
  • 相关阅读:
    股指期货风声水起 股市"蛇人″给我们启示
    Goals of Distributed Application Design
    火箭股票,火箭发射(07.4.12)
    SQLAlchemy完全入门
    巧用异或
    FastAPI启用HTTPS
    错误记录:Can't connect to MySQL server on xxx
    MySQL常用命令
    就是想写点什么
    Android关于Activity class {package/class} does not exist
  • 原文地址:https://www.cnblogs.com/iwangzhengchao/p/9853315.html
Copyright © 2011-2022 走看看