解法
典型的深度优先遍历,注意isVisted的置1和置0
代码
class Solution { public boolean exist(char[][] board, String word) { int[][] isVisited = new int[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if(f(board,isVisited,word,0,i,j)) return true; } } return false; } public boolean f(char[][] board, int[][] isVisited, String word, int index, int i, int j) { if (index==word.length()) return true; //超过了边界 if (i > board.length-1||j > board[0].length-1||j<0||i<0) return false; //已经走过了 if (isVisited[i][j] == 1) return false; if (board[i][j] == word.charAt(index)) { isVisited[i][j] = 1;//标志为已经走过 //走下一步 if ( !f(board, isVisited, word, index + 1, i, j + 1) && !f(board, isVisited, word, index + 1, i, j - 1) && !f(board, isVisited, word, index + 1, i + 1, j) && !f(board, isVisited, word, index + 1, i - 1, j)){ isVisited[i][j]=0; return false; } } else return false; return true; } }