|
| 1 | +# 1) Use dfs and backtracking to search for a word in the board. |
| 2 | +# TC: O(N*M*3^W) where N is len(row), M is len(col) and W is len(word) |
| 3 | +# SC: O(N*M) representing the maximum depth of the recursion tack. |
| 4 | +class Solution: |
| 5 | + def dfs(self, board: List[List[str]], word: str, row: int, col: int, word_idx: int) -> bool: |
| 6 | + if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]): |
| 7 | + return False |
| 8 | + |
| 9 | + if word_idx >= len(word) or board[row][col] != word[word_idx]: |
| 10 | + return False |
| 11 | + |
| 12 | + if word_idx == len(word) - 1: |
| 13 | + return True |
| 14 | + |
| 15 | + temp = board[row][col] |
| 16 | + board[row][col] = '#' |
| 17 | + |
| 18 | + found = ( |
| 19 | + self.dfs(board, word, row + 1, col, word_idx + 1) or |
| 20 | + self.dfs(board, word, row - 1, col, word_idx + 1) or |
| 21 | + self.dfs(board, word, row, col + 1, word_idx + 1) or |
| 22 | + self.dfs(board, word, row, col - 1, word_idx + 1) |
| 23 | + ) |
| 24 | + |
| 25 | + board[row][col] = temp |
| 26 | + |
| 27 | + return found |
| 28 | + |
| 29 | + def exist(self, board: List[List[str]], word: str) -> bool: |
| 30 | + row_len = len(board) |
| 31 | + column_len = len(board[0]) |
| 32 | + word_len = len(word) |
| 33 | + |
| 34 | + # Early return if the board contains fewer cells than the word length. |
| 35 | + if row_len * column_len < word_len: return False |
| 36 | + |
| 37 | + for i in range(row_len): |
| 38 | + for j in range(column_len): |
| 39 | + if self.dfs(board, word, i, j, 0): |
| 40 | + return True |
| 41 | + |
| 42 | + return False |
0 commit comments