11// 12. 矩阵中的路径
22
33
4+ // 新版
5+ public class Solution {
6+ public boolean hasPath (char [][] matrix , String word ) {
7+ char [] words = word .toCharArray ();
8+ for (int i = 0 ; i < matrix .length ; i ++) {
9+ for (int j = 0 ; j < matrix [0 ].length ; j ++) {
10+ if (bfs (matrix , words , i , j , 0 )) {
11+ return true ;
12+ }
13+ }
14+ }
15+ return false ;
16+ }
17+
18+ public boolean bfs (char [][] matrix , char [] words , int i , int j , int index ) {
19+ if (i < 0 || i >= matrix .length || j < 0 || j >= matrix [0 ].length || matrix [i ][j ] != words [index ]) {
20+ return false ;
21+ }
22+ if (index == words .length - 1 ) {
23+ return true ;
24+ }
25+ char temp = matrix [i ][j ];
26+ matrix [i ][j ] = '.' ;
27+ boolean result = bfs (matrix , words , i - 1 , j , index + 1 ) ||
28+ bfs (matrix , words , i + 1 , j , index + 1 ) ||
29+ bfs (matrix , words , i , j - 1 , index + 1 ) ||
30+ bfs (matrix , words , i , j + 1 , index + 1 );
31+ matrix [i ][j ] = temp ;
32+ return result ;
33+ }
34+ }
35+
36+
37+ // 旧版
438public class Solution {
539 public boolean hasPath (char [] matrix , int rows , int cols , char [] str ) {
640 boolean [] flag = new boolean [matrix .length ];
@@ -30,11 +64,8 @@ private boolean judge(char[] matrix, int rows, int cols, boolean[] flag, char[]
3064 judge (matrix , rows , cols , flag , str , i + 1 , j , k + 1 ) || // 下
3165 judge (matrix , rows , cols , flag , str , i , j - 1 , k + 1 ) || // 左
3266 judge (matrix , rows , cols , flag , str , i , j + 1 , k + 1 ); // 右
33- if (res ) {
34- return true ;
35- }
36- // 此路不通,回溯还原
67+ // 回溯还原
3768 flag [index ] = false ;
38- return false ;
69+ return res ;
3970 }
4071}
0 commit comments