zoukankan      html  css  js  c++  java
  • 矩阵中的路径

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 egin{bmatrix} a & b & c &e \ s & f & c & s \ a & d & e& e\ end{bmatrix}quadasabfdcceese  矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
     
     
     1 public class Solution {
     2     public boolean dfs(int x, int y, char[] matrix, int rows, int cols, char[] str, int pos, boolean[][]vis) {
     3         int [][]shift = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
     4         boolean flag = false;
     5         if (pos == str.length) return true;
     6         for (int i = 0; i < 4; ++i) {
     7             int posx = x + shift[i][0];
     8             int posy = y + shift[i][1];
     9             if (flag) return true;
    10             if (posx < rows && posy < cols && posx >= 0 && posy >= 0 && !vis[posx][posy]) {
    11                 char c = matrix[posx * cols + posy];
    12                 if (c == str[pos]) {
    13                     vis[posx][posy] = true;
    14                     flag = flag || dfs(posx, posy, matrix, rows, cols, str, pos + 1, vis);
    15                     vis[posx][posy] = false;
    16                 }
    17             }
    18         }
    19         return flag;
    20         
    21     }
    22     public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    23     {
    24         
    25         boolean [][]vis = new boolean [rows + 1][cols + 1];
    26         boolean flag = false;
    27         
    28         for (int i = 0; i < rows; ++i) {
    29             for (int j = 0; j < cols; ++j) {
    30                 char c = matrix[i * cols + j];
    31                 if(flag) return true;
    32                 if (c == str[0]) {
    33                     vis[i][j] = true;
    34                     flag = flag || dfs(i, j, matrix, rows, cols, str, 1, vis);
    35                     vis[i][j] = false;
    36                 }
    37             }
    38         }
    39         return flag;
    40     }
    41 
    42 
    43 }
  • 相关阅读:
    每次运行caffe代码之前需要考虑修改的地方
    caffe solver 配置详解
    python获取当前文件路径以及父文件路径
    Python 文件夹及文件操作
    安装NVIDIA驱动时禁用自带nouveau驱动
    博客园转载其他博客园的文章:图片和源码
    分布式开放消息系统(RocketMQ)的原理与实践
    RocketMQ基本概念及原理介绍
    rocketmq 4.3.2 解决远程不能消费问题,解决未识别到公网IP问题
    osx免驱网卡推荐
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12300983.html
Copyright © 2011-2022 走看看