|
| 1 | +var exist = function (board, word) { |
| 2 | + const rowLen = board.length, colLen = board[0].length; |
| 3 | + let visited = new Set(); // keep track of visited coordinates |
| 4 | + |
| 5 | + function dfs(row, col, idx) { |
| 6 | + if (idx === word.length) return true; // if idx equals word.length, it means the word exists |
| 7 | + if (row < 0 || col < 0 || |
| 8 | + row >= rowLen || col >= colLen || |
| 9 | + board[row][col] !== word[idx] || |
| 10 | + visited.has(`${row}|${col}`)) return false; // possible cases that would return false |
| 11 | + |
| 12 | + |
| 13 | + // backtracking |
| 14 | + visited.add(`${row}|${col}`); |
| 15 | + let result = dfs(row + 1, col, idx + 1) || // dfs on all 4 directions |
| 16 | + dfs(row - 1, col, idx + 1) || |
| 17 | + dfs(row, col + 1, idx + 1) || |
| 18 | + dfs(row, col - 1, idx + 1); |
| 19 | + visited.delete(`${row}|${col}`); |
| 20 | + |
| 21 | + return result; |
| 22 | + } |
| 23 | + |
| 24 | + for (let row = 0; row < rowLen; row++) { |
| 25 | + for (let col = 0; col < colLen; col++) { |
| 26 | + if(dfs(row, col, 0)) return true; // dfs for all coordinates |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return false; |
| 31 | +}; |
| 32 | + |
| 33 | +// 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 | +// space - O(m * n + w) |
0 commit comments