|
| 1 | +// TC: O(n * m * 4^k); |
| 2 | +// -> The size of board: n * m |
| 3 | +// -> Check 4 directions by the given word's length: 4^k |
| 4 | +// SC: O(n * m + k) |
| 5 | +// -> boolean 2D array: n * M |
| 6 | +// -> recursive max k spaces |
| 7 | +class Solution { |
| 8 | + public boolean exist(char[][] board, String word) { |
| 9 | + // Mark visited path to do not go back. |
| 10 | + boolean[][] visit = new boolean[board.length][board[0].length]; |
| 11 | + |
| 12 | + for (int i = 0; i < board.length; i++) { |
| 13 | + for (int j = 0; j < board[0].length; j++) { |
| 14 | + if (wordSearch(i, j, 0, word, board, visit)) return true; |
| 15 | + } |
| 16 | + } |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + private boolean wordSearch(int i, int j, int idx, String word, char[][] board, boolean[][] visit) { |
| 21 | + |
| 22 | + // When idx checking reach to the end of the length of the word then, return true |
| 23 | + if (idx == word.length()) return true; |
| 24 | + |
| 25 | + // Check if i and j are inside of the range |
| 26 | + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; |
| 27 | + |
| 28 | + // Check if the coordinate equals to the charactor value |
| 29 | + if (board[i][j] != word.charAt(idx)) return false; |
| 30 | + if (visit[i][j]) return false; |
| 31 | + |
| 32 | + // Mark the coordinate as visited |
| 33 | + visit[i][j] = true; |
| 34 | + |
| 35 | + // If visited, the target is gonna be the next charactor |
| 36 | + idx += 1; |
| 37 | + |
| 38 | + // If any direction returns true then it is true |
| 39 | + if ( |
| 40 | + wordSearch(i+1, j, idx, word, board, visit) || |
| 41 | + wordSearch(i-1, j, idx, word, board, visit) || |
| 42 | + wordSearch(i, j+1, idx, word, board, visit) || |
| 43 | + wordSearch(i, j-1, idx, word, board, visit) |
| 44 | + ) return true; |
| 45 | + |
| 46 | + // If visited wrong direction, turns it as false |
| 47 | + visit[i][j] = false; |
| 48 | + |
| 49 | + return false; |
| 50 | + } |
| 51 | +} |
0 commit comments