Word Search
1 public class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(!isValidBoard(board) || word == null || word.length() == 0) { 4 return false; 5 } 6 7 boolean[][] visitedMap = new boolean[board.length][board[0].length]; 8 for(int i = 0; i < board.length; i++) { 9 for(int j = 0; j < board[i].length; j++) { 10 if(contains(board, visitedMap, word, i, j, 0)) { 11 return true; 12 } 13 } 14 } 15 16 return false; 17 } 18 19 private boolean isValidBoard(char[][] board) { 20 if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) { 21 return false; 22 } else { 23 return true; 24 } 25 } 26 27 private boolean contains(char[][] board, boolean[][] visitedMap, String word, int i, int j, int index) { 28 if(index >= word.length() || visitedMap[i][j] == true) { 29 return false; 30 } else if(index == word.length()-1 && board[i][j] == word.charAt(index)) { 31 return true; 32 } 33 34 if(board[i][j] == word.charAt(index)) { 35 visitedMap[i][j] = true; 36 37 // upper 38 if(i > 0 && contains(board, visitedMap, word, i-1, j, index+1)) { 39 return true; 40 } 41 42 // down 43 if(i < board.length-1 && contains(board, visitedMap, word, i+1, j, index+1)) { 44 return true; 45 } 46 47 // left 48 if(j > 0 && contains(board, visitedMap, word, i, j-1, index+1)) { 49 return true; 50 } 51 52 // right 53 if(j < board[i].length-1 && contains(board, visitedMap, word, i, j+1, index+1)) { 54 return true; 55 } 56 57 visitedMap[i][j] = false; 58 } 59 60 return false; 61 } 62 63 }