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