矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 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的形式;

posted @ 2020-06-27 15:38  打屎也不熬夜  阅读(81)  评论(0编辑  收藏  举报