問題描述
思路
DFS經典問題。沒啥好說的。說點技巧把。 方向數組的應用,剪枝的應用。
方法一
import java.util.*;
public class Solution {
private int rows, cols;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if(matrix == null || matrix.length == 0 || str == null || str.length == 0) return false;
this.rows = rows; this.cols = cols;
for(int row = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
if(matrix[getIndex(row,col)] == str[0]){
if(logic(matrix, row, col, str, 0, new boolean[matrix.length])) return true;
}
}
}
return false;
}
public boolean logic(char[] matrix, int row, int col, char[] str, int strIndex, boolean[] isVisited){
if(isVisited[getIndex(row,col)] || matrix[getIndex(row,col)] != str[strIndex]) return false;
// 能走到這裏, 證明肯定是相等的
if(strIndex == str.length-1) return true;
isVisited[getIndex(row,col)] = true;
int[] direcX = new int[]{1,0,-1,0};
int[] direcY = new int[]{0,1,0,-1};
for(int step = 0; step < 4; step++){
int curX = row + direcX[step], curY = col + direcY[step];
if(curX<0 || curX>=rows || curY<0 || curY>=cols || isVisited[getIndex(curX,curY)]) continue;
// 剪枝操作
if(logic(matrix, curX, curY, str, strIndex+1, isVisited)) return true;
isVisited[getIndex(curX,curY)] = false;
}
return false;
}
private int getIndex(int row, int col){
return row * cols + col;
}
}