題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
Solution
回溯法,使用一個狀態數組保存格子訪問狀態
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
int[] f = new int[matrix.length];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (move(matrix, rows, cols, i, j, str, 0, f)) {
return true;
}
}
}
return false;
}
public boolean move(char[] matrix, int rows, int cols, int i, int j, char[] str, int k, int[] f) {
int pos = i * cols + j;
if (i < 0 || i >= rows || j < 0 || j >= cols || pos >= matrix.length || f[pos] == 1) {
return false;
}
if (matrix[pos] != str[k]) {
return false;
}
f[pos] = 1; //該格子被訪問
if (k >= str.length-1) {
return true;
}
if (move(matrix, rows, cols, i-1, j, str, k+1, f) ||
move(matrix, rows, cols, i+1, j, str, k+1, f) ||
move(matrix, rows, cols, i, j-1, str, k+1, f) ||
move(matrix, rows, cols, i, j+1, str, k+1, f)) {
return true; //路徑通了一路返回true
}
f[pos] = 0; //當前格子路徑不通,格子狀態改回未訪問
return false;
}
}