|
| 1 | +// Space Complexity O(m * n + w) approach |
1 | 2 | var exist = function (board, word) {
|
2 | 3 | const rowLen = board.length, colLen = board[0].length;
|
3 | 4 | let visited = new Set(); // keep track of visited coordinates
|
@@ -32,3 +33,37 @@ var exist = function (board, word) {
|
32 | 33 |
|
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
|
34 | 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