DFS
1 public class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(word == null || word.length() < 1) 4 return false; 5 HashSet<Integer> done = new HashSet<Integer>(); 6 7 for(int i = 0; i < board.length; i++) 8 for(int j =0; j < board[0].length; j++){ 9 if(generate(board, i, j, 0, word, done)) 10 return true; 11 } 12 13 return false; 14 } 15 16 private boolean generate(char[][] board, int row, int column, int depth, String word, HashSet<Integer> done){ 17 if(row < 0 || column < 0 || row >= board.length || column >= board[0].length) 18 return false; 19 int loc = row * board[0].length + column; 20 if(done.contains(loc)) 21 return false; 22 if(board[row][column] == word.charAt(depth)){ 23 if(depth == word.length()-1) 24 return true; 25 done.add(loc); 26 if(generate(board, row+1, column, depth+1,word,done)) 27 return true; 28 if(generate(board, row, column+1, depth+1,word,done)) 29 return true; 30 if(generate(board, row-1, column, depth+1,word,done)) 31 return true; 32 if(generate(board, row, column-1, depth+1,word,done)) 33 return true; 34 done.remove(loc); 35 } 36 return false; 37 } 38 }