題目描述
分析
利用回溯法,從矩陣任一點開始,向四周試探,若滿足字符順序,則走一步並繼續試探,直到字符串搜索結束返回true。如果都不滿足,則回溯繼續搜索。由於不能重複走同一個格子,需要一個額外的布爾數組記錄走過的路徑,同時,在回溯時要將走過的當前格子標記清除。
代碼(已AC)
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
boolean[] flags = new boolean[matrix.length];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(judge(matrix,i,j,rows,cols,str,0,flags)) return true;
}
}
return false;
}
public boolean judge(char[] matrix,int i, int j, int rows, int cols, char[] str, int idx, boolean[] flags){
int index = i*cols+j;
if(i<0 || j<0 || i>=rows || j>=cols || flags[index] || matrix[index]!=str[idx]) return false;
if(idx == str.length-1) return true;
flags[index] = true;
if( judge(matrix, i+1, j, rows, cols, str, idx+1, flags) ||
judge(matrix, i-1, j, rows, cols, str, idx+1, flags) ||
judge(matrix, i, j+1, rows, cols, str, idx+1, flags) ||
judge(matrix, i, j-1, rows, cols, str, idx+1, flags))
return true;
flags[index] = false; // 回溯
return false;
}
}