public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m][n]; int len = word.length(); int k = 0; for(int i = 0;i<m;i++){ for(int j = 0;j<n;j++){ if(board[i][j] == word.charAt(0)){ if(find(i,j,m,n,len,k,board,word,visited)){ return true; } } } } return false; } private boolean find(int i, int j, int m, int n,int len, int k, char[][] board, String word, boolean[][] visited) { //搜索该位置的上(i-1,j)下(i+1,j)左(i,j-1)右(i,j+1),看是否能找到下一个字符 if(i<0 || i>=m || j<0 || j>=n) return false; if(!visited[i][j]){ if(board[i][j] == word.charAt(k)) { if(k == len-1) return true; if(i>0){ visited[i][j] = true; if(find(i - 1, j, m, n, len, k + 1,board,word,visited)){ return true; } visited[i][j] = false; } if(i<m-1){ visited[i][j] = true; if(find(i + 1, j, m, n, len, k + 1,board,word,visited)){ return true; } visited[i][j] = false; } if(j>0){ visited[i][j] = true; if(find(i, j - 1, m, n, len, k + 1,board,word,visited)){ return true; } visited[i][j] = false; } if(j<n-1){ visited[i][j] = true; if(find(i, j + 1, m, n, len, k + 1,board,word,visited)){ return true; } visited[i][j] = false; } } } return false; }