标签:lse 存在 pre ted pat null 传引用 efault thml
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的形式;
标签:lse 存在 pre ted pat null 传引用 efault thml
原文地址:https://www.cnblogs.com/Susie2world/p/13198522.html