题解 | #矩阵中的路径#
矩阵中的路径
http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
进行DFS遍历,每次到一个位置先判断是否能匹配word中的一个,能才踩下去
int[][] dirs = {{0,-1},{0,1},{-1,0},{1,0}};//左,右,上,下
public boolean hasPath (char[][] matrix, String word) {
//思路:遍历数组,从随意row,col出发,去过的位置用一个boolean二维数组进行标记
if(matrix==null||matrix.length==0) return false;
//每一步都进行判断,相同才尝试去走
int rows = matrix.length;
int cols = matrix[0].length;
char[] words = word.toCharArray();
boolean[][] isCame = new boolean[rows][cols];//标记一个位置是否走过
for(int row = 0;row<rows;row++){
for(int col = 0;col<cols;col++){
if(canGetWord(matrix,words,0,row,col,isCame,rows,cols)){
return true;
}
}
}
return false;
}
//来到row,col位置,还没踩下去
public boolean canGetWord(char[][] matrix,char[] words,
int idx,int row,int col,
boolean[][] isCame,int rows,int cols){
if(idx==words.length) return true;
if(row<0||row>=rows||col<0||col>=cols||matrix[row][col]!=words[idx]||isCame[row][col]) return false;
//尝试往四个方向走
boolean res = false;
for(int[] dir:dirs){
isCame[row][col] = true;//踩下去
if(canGetWord(matrix,words,idx+1,row+dir[0],col+dir[1],isCame,rows,cols)){
res = true;
}
isCame[row][col] = false;//轨迹擦除
}
return res;
} waigo的刷题之路 文章被收录于专栏
收录平时刷题的题解
查看9道真题和解析