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

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
     
    题解:
      使用回溯法,进行深度遍历,并设置一个visit来标记时候遍历过
     
      
     1 class Solution {
     2 public:
     3     bool hasPath(char* matrix, int rows, int cols, char* str)
     4     {
     5         if (matrix == nullptr || rows < 1 || cols < 1)return false;
     6         if (str == nullptr)return true;
     7         vector<bool>visit(rows*cols, false);
     8         int pot = 0;
     9         for (int i = 0; i < rows; ++i)
    10             for (int j = 0; j < cols; ++j)
    11                 if (DFS(matrix, rows, cols, i, j, visit, str, pot))
    12                     return true;
    13         return false;
    14     }
    15     bool DFS(const char* matrix, const int rows, const int cols,int i, int j, vector<bool>&visit,const char *str, int &pot)
    16     {
    17         if (str[pot] == '')return true;
    18         bool flag = false;
    19         if (i >= 0 && i < rows && j >= 0 && j < cols &&
    20             matrix[i*cols + j] == str[pot] && visit[i*cols + j] == false)
    21         {
    22             ++pot;
    23             visit[i*cols + j] = true;
    24             flag = DFS(matrix, rows, cols, i + 1, j, visit, str, pot) ||
    25                     DFS(matrix, rows, cols, i - 1, j, visit, str, pot) ||
    26                     DFS(matrix, rows, cols, i, j + 1, visit, str, pot) ||
    27                     DFS(matrix, rows, cols, i, j - 1, visit, str, pot);
    28             if (flag == false)
    29             {
    30                 --pot;
    31                 visit[i*cols + j] = false;//回溯
    32             }
    33         }
    34         return flag;
    35     }
    36 };
  • 相关阅读:
    什么是看板方法?
    瓶颈法则
    累积流图——你还没有用过吗?
    为什么我们关注看板方法?
    蒟蒻报道
    博客更换通知
    浅谈树套树(线段树套平衡树)&学习笔记
    浅谈FFT(快速博立叶变换)&学习笔记
    题解 洛谷P1903/BZOJ2120【[国家集训队]数颜色 / 维护队列】
    题解 洛谷P4550/BZOJ1426 【收集邮票】
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11654816.html
Copyright © 2011-2022 走看看