单词搜索
解题思路:递归+dfs+回溯
class Solution { public boolean exist(char[][] board, String word) { int xlen = board.length; int ylen = board[0].length; int slen = word.length(); int t = 0; boolean[][] flags = new boolean[xlen][ylen]; for(int i=0;i<xlen;++i){ for(int j=0;j<ylen;++j){ if(validate(board,xlen,ylen,slen,i,j,word,flags,0)){ return true; } for(int m=0;m<xlen;++m){ for(int n=0;n<ylen;++n){ if(flags[m][n]){ flags[m][n]=false; } } } } } return false; } public boolean validate(char[][] board,int xlen,int ylen, int slen, int i, int j, String word, boolean[][] flags,int t){ if(t==slen){ return true; } if(i<0||i>=xlen||j<0||j>=ylen){ return false; } if(flags[i][j]==false&&board[i][j]==word.charAt(t)){ flags[i][j] = true; if(validate(board,xlen,ylen,slen,i-1,j,word,flags,t+1)|| validate(board,xlen,ylen,slen,i,j-1,word,flags,t+1)|| validate(board,xlen,ylen,slen,i+1,j,word,flags,t+1)|| validate(board,xlen,ylen,slen,i,j+1,word,flags,t+1)){ return true; } flags[i][j]=false; } return false; } }