package jianzhioffer;
/**
- 矩阵中搜寻路径,一般方法都是dfs,首先找到第一个字母的位置,然后从该字母开始进行上下左右四个方向上的尝试判断即可
- dfs停止的边界条件便是碰到矩阵的边界或者碰到已经访问过的格子或者和条件不符合
- 此题可以直接用给定的矩阵用作记录已经走过的路径。
- */
class Solution {
public boolean exist(char[][] board, String word) {
boolean re=false;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]word.charAt(0))
{
re=exit(board,word,i,j,0);
if(re) return re;
}
}
}
return re;
}
public boolean exit(char[][] b,String word,int x,int y,int index){
if(index>=word.length()) return true;
if(x<0||x>=b.length||y<0||y>=b[0].length||b[x][y]’-’) return false;
if(b[x][y]!=word.charAt(index)) return false;
char temp=b[x][y];
b[x][y]=’-’;
boolean re=exit(b,word,x+1,y,index+1);
if(!re) re=exit(b,word,x,y+1,index+1);
if(!re) re=exit(b,word,x-1,y,index+1);
if(!re) re=exit(b,word,x,y-1,index+1);
b[x][y]=temp;
return re;
}
}