|
| 1 | +package medium; |
| 2 | + |
| 3 | +public class WordSearch { |
| 4 | +//I made it this time, completely by myself! Cheers! This let me completely understand backtracking! |
| 5 | + public boolean exist(char[][] board, String word) { |
| 6 | + int m = board.length, n = board[0].length; |
| 7 | + for(int i = 0; i < m; i++){ |
| 8 | + for(int j = 0; j < n; j++){ |
| 9 | + boolean[][] visited = new boolean[m][n]; |
| 10 | + if(dfs(board, visited, i, j, word, 0)) return true; |
| 11 | + } |
| 12 | + } |
| 13 | + return false; |
| 14 | + } |
| 15 | + |
| 16 | + final int[] dirs = new int[]{0,1,0,-1,0}; |
| 17 | + |
| 18 | + boolean dfs(char[][] board, boolean[][] visited, int row, int col, String word, int index){ |
| 19 | + if(index >= word.length() || word.charAt(index) != board[row][col]) return false; |
| 20 | + else if(index == word.length()-1 && word.charAt(index) == board[row][col]) { |
| 21 | + visited[row][col] = true; |
| 22 | + return true; |
| 23 | + } |
| 24 | + visited[row][col] = true;//set it to true for this case |
| 25 | + boolean result = false; |
| 26 | + for(int i = 0; i < 4; i++){ |
| 27 | + int nextRow = row+dirs[i]; |
| 28 | + int nextCol = col+dirs[i+1]; |
| 29 | + if(nextRow < 0 || nextRow >= board.length || nextCol < 0 || nextCol >= board[0].length || visited[nextRow][nextCol]) continue; |
| 30 | + result = dfs(board, visited, nextRow, nextCol, word, index+1); |
| 31 | + if(result) return result; |
| 32 | + else visited[nextRow][nextCol] = false;//set it back to false if this road doesn't work to allow it for other paths, this is backtracking!!! |
| 33 | + } |
| 34 | + return result; |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String...strings){ |
| 38 | + WordSearch test = new WordSearch(); |
| 39 | +// char[][] board = new char[][]{ |
| 40 | +// {'A','B','C','E'}, |
| 41 | +// {'S','F','C','S'}, |
| 42 | +// {'A','D','E','E'}, |
| 43 | +// }; |
| 44 | +// String word = "ABCCED"; |
| 45 | +// String word = "SEE"; |
| 46 | +// String word = "ABCD"; |
| 47 | + |
| 48 | +// char[][] board = new char[][]{ |
| 49 | +// {'a','a'}, |
| 50 | +// }; |
| 51 | +// String word = "aaa"; |
| 52 | + |
| 53 | + char[][] board = new char[][]{ |
| 54 | + {'A','B','C','E'}, |
| 55 | + {'S','F','E','S'}, |
| 56 | + {'A','D','E','E'}, |
| 57 | + }; |
| 58 | + String word = "ABCEFSADEESE"; |
| 59 | + System.out.println(test.exist(board, word)); |
| 60 | + } |
| 61 | +} |
0 commit comments