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

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
    例如 a,b,c,e;   s,f,c,s;    a,d,e,e
    矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
     
     1 public class Solution {
     2      
     3     public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
     4         if(matrix==null || matrix.length==0 || str==null || str.length==0 || matrix.length!=rows*cols || rows<=0 || cols<=0 || rows*cols < str.length) {
     5             return false ;
     6         }
     7  
     8         boolean[] visited = new boolean[rows*cols] ;
     9          
    10         for(int i=0 ; i<=rows-1 ; i++) {
    11             for(int j=0 ; j<=cols-1 ; j++) {
    12                 if(hasPathCore(matrix, rows, cols, str, i, j, visited, 0)) { return true ; }
    13             }
    14         }
    15  
    16         return false ;
    17     }
    18      
    19     public boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, int row, int col, boolean[] visited, int t) {
    20         boolean flag = false ;
    21  
    22         if(row>=0 && row<rows && col>=0 && col<cols && !visited[row*cols+col] && matrix[row*cols+col]==str[t]) {
    23             t++ ;
    24             visited[row*cols+col] = true ;
    25             if(t==str.length) { return true ; }
    26             flag = hasPathCore(matrix, rows, cols, str, row, col+1, visited, t)  ||
    27                    hasPathCore(matrix, rows, cols, str, row+1, col, visited, t)  ||
    28                    hasPathCore(matrix, rows, cols, str, row, col-1, visited, t)  ||
    29                    hasPathCore(matrix, rows, cols, str, row-1, col, visited, t) ;
    30  
    31             if(!flag) {
    32                 t-- ;
    33                 visited[row*cols+col] = false ;
    34             }
    35         }
    36  
    37         return flag ;
    38     }
    39      
    40 }

    如果想像C++那样传引用形参的话,可以使用int[] temp={0}; int[] temp的形式;

  • 相关阅读:
    Asp:Cookies应用指南
    asp:cookies的属性
    数据库压缩
    asp之servervariables全部显示
    sql语句操作表
    asp之FSO大全
    SQL语句
    vbscript语句
    asp之vbscript函数
    IDEA 2017web项目的创建
  • 原文地址:https://www.cnblogs.com/Susie2world/p/13198522.html
Copyright © 2011-2022 走看看