classSolution{//回溯法 dfspublicbooleanexist(char[][] board, String word){for(int i =0; i < board.length; i ++)for(int j =0; j < board[0].length; j ++)if(dfs(board, word,0, i, j))returntrue;returnfalse;}privatebooleandfs(char[][] board, String word,int u,int x,int y){if( x >= board.length || x <0|| y >= board[0].length || y <0||board[x][y]!= word.charAt(u)){returnfalse;}//if后判断if(u == word.length()-1)returntrue;//用于回溯char temp = board[x][y];
board[x][y]='*';//递归遍历,不用dr和dl数组,更简洁明了。boolean res =dfs(board, word, u+1, x -1, y)||dfs(board, word, u+1, x+1, y)||dfs(board, word, u+1, x, y-1)||dfs(board, word, u+1, x, y+1);
board[x][y]= temp;return res;}}