题目描述:
思路:可以先寻找数组中和第一个字符相同的字符的位置,之后按上下左右顺序依次查找。但是查找第一个字符可以和查找后面字符相结合。
class Solution {
public boolean exist(char[][] board, String word) {
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(exists(board,word,0,i,j))return true;
}
}
return false;
}
public boolean exists(char[][] board, String word,int step,int x,int y){
if(x>=board.length||x<0||y>=board[0].length||y<0||board[x][y] != word.charAt(step))return false;
if(step==word.length()-1)return true;
char tem=board[x][y];
board[x][y]=' ';
boolean result=exists(board, word,step+1,x+1,y)||exists(board, word,step+1,x-1,y)||exists(board, word,step+1,x,y+1)||exists(board, word,step+1,x,y-1);
board[x][y]=tem;
return result;
}
}