|
| 1 | +// Space Complexity O(m * n + w) approach |
| 2 | +var exist = function (board, word) { |
| 3 | + const rowLen = board.length, colLen = board[0].length; |
| 4 | + let visited = new Set(); // keep track of visited coordinates |
| 5 | + |
| 6 | + function dfs(row, col, idx) { |
| 7 | + if (idx === word.length) return true; // if idx equals word.length, it means the word exists |
| 8 | + if (row < 0 || col < 0 || |
| 9 | + row >= rowLen || col >= colLen || |
| 10 | + board[row][col] !== word[idx] || |
| 11 | + visited.has(`${row}|${col}`)) return false; // possible cases that would return false |
| 12 | + |
| 13 | + |
| 14 | + // backtracking |
| 15 | + visited.add(`${row}|${col}`); |
| 16 | + let result = dfs(row + 1, col, idx + 1) || // dfs on all 4 directions |
| 17 | + dfs(row - 1, col, idx + 1) || |
| 18 | + dfs(row, col + 1, idx + 1) || |
| 19 | + dfs(row, col - 1, idx + 1); |
| 20 | + visited.delete(`${row}|${col}`); |
| 21 | + |
| 22 | + return result; |
| 23 | + } |
| 24 | + |
| 25 | + for (let row = 0; row < rowLen; row++) { |
| 26 | + for (let col = 0; col < colLen; col++) { |
| 27 | + if(dfs(row, col, 0)) return true; // dfs for all coordinates |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return false; |
| 32 | +}; |
| 33 | + |
| 34 | +// time - O(m * n * 4^w) traverse through the matrix (m * n) and run dfs on each of the possible paths (4^w) 4 being 4 directions |
| 35 | +// space - O(m * n + w) |
| 36 | + |
| 37 | +// Space Complexity O(1) approach |
| 38 | +var exist = function (board, word) { |
| 39 | + const rowLen = board.length, colLen = board[0].length; |
| 40 | + |
| 41 | + function dfs(row, col, idx) { |
| 42 | + if (idx === word.length) return true; |
| 43 | + if (row < 0 || col < 0 || |
| 44 | + row >= rowLen || col >= colLen || |
| 45 | + board[row][col] !== word[idx]) return false; |
| 46 | + |
| 47 | + const letter = board[row][col]; |
| 48 | + board[row][col] = '#' |
| 49 | + let result = dfs(row + 1, col, idx + 1) || |
| 50 | + dfs(row - 1, col, idx + 1) || |
| 51 | + dfs(row, col + 1, idx + 1) || |
| 52 | + dfs(row, col - 1, idx + 1); |
| 53 | + board[row][col] = letter |
| 54 | + |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + for (let row = 0; row < rowLen; row++) { |
| 59 | + for (let col = 0; col < colLen; col++) { |
| 60 | + if (board[row][col] === word[0] && |
| 61 | + dfs(row, col, 0)) return true; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return false; |
| 66 | +}; |
| 67 | + |
| 68 | +// time - O(m * n * 4^w) traverse through the matrix (m * n) and run dfs on each of the possible paths (4^w) 4 being 4 directions |
| 69 | +// space - O(1) |
0 commit comments