(劍指offer)矩陣中的路徑
阿新 • • 發佈:2018-12-09
時間限制:1秒 空間限制:32768K 熱度指數:122033
題目描述
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
//回溯法
boolean[] flag = new boolean[matrix.length];//引用型別的有預設初始化值
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(check(matrix, rows, cols, i, j, flag, str, 0)){
return true;
}
}
}
return false;
}
public boolean check(char[] matrix, int rows, int cols, int i, int j, boolean[] flag, char[] str, int cnt){
int index = i*cols + j;//二維與一維對應
//遞迴結束(無法滿足)
if(i < 0 || i >= rows || j < 0 || j >= cols || flag[index] == true || matrix[index] != str[cnt]){
return false;
}
//遞迴結束(滿足)
if(cnt == str.length -1){
return true;
}
//遞迴不結束,走當前這一步
flag[index] = true;
//四個方向遞迴呼叫
if(check(matrix, rows, cols, i-1, j, flag, str, cnt+1) ||
check(matrix, rows, cols, i+1, j, flag, str, cnt+1) ||
check(matrix, rows, cols, i, j-1, flag, str, cnt+1) ||
check(matrix, rows, cols, i, j+1, flag, str, cnt+1)){
return true;
}
//回溯(一旦此路不通,回去)
flag[index] = false;
return false;
}
}