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

    题目描述

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

    思路:

    1、遍历每一个点,判断从当前点开始,是否存在某条路径(help 函数的功能)

    2、如何判断从某个点开始是否存在某条路径?

    从当前点开始,判断此点的上下左右是否存在某条路径。不断地递归。

    PS:建立一个flag数组,存储当前节点是否被访问过。

     1 public class Solution {
     2     public boolean hasPath(char[] matrix, int rows, int cols, char[] str){
     3         int[] flag = new int[matrix.length];
     4         for(int i = 0;i < rows;i++)
     5             for(int j = 0;j < cols;j++)
     6                 if(help(matrix,rows,cols,str,i,j,0,flag))
     7                     return true;
     8         return false;
     9     }
    10     private boolean help(char[] matrix,int rows,int cols,char[] str,int i ,int j,int k ,int[] flag){
    11         int index = i*cols+j;
    12         if (i<0 || i>=rows ||j<0 || j>=cols || flag[index]==1 || matrix[index]!=str[k])
    13             //越界 已经被访问过,与当前值不相等
    14             return false;
    15         if(k==str.length-1)//全部匹配
    16             return true;
    17         flag[index] = 1;
    18         if(help(matrix,rows,cols,str,i-1,j,k+1,flag)||
    19            help(matrix,rows,cols,str,i+1,j,k+1,flag)||
    20            help(matrix,rows,cols,str,i,j-1,k+1,flag)||
    21            help(matrix,rows,cols,str,i,j+1,k+1,flag))
    22             return true;
    23         flag[index] = 0;//条件不符合,还原为未访问过的标记
    24         return false;//条件不符合
    25     }
    26 }
  • 相关阅读:
    bzoj 3456 城市规划 —— 分治FFT / 多项式求逆 / 指数型生成函数(多项式求ln)
    洛谷 P4721 [模板]分治FFT —— 分治FFT / 多项式求逆
    CF 438 E & bzoj 3625 小朋友和二叉树 —— 多项式开方
    Codeforces 447
    Codeforces 1099
    Codeforces 991
    Codeforces 994
    Codeforces 989
    Codeforces 1084
    xj膜你赛(n-1)
  • 原文地址:https://www.cnblogs.com/zle1992/p/8318647.html
Copyright © 2011-2022 走看看