|
| 1 | +# M, N are dimensions of the board, W is the number of words, and L is the maximum length of a word. |
| 2 | +# TC: O(W * L + M * N * 3^(L - 1)) - building Trie takes O(W * L); backtracking explores at most 3 directions after first step up to depth L |
| 3 | +# SC: O(W * L) - Trie storage for all words and recursion stack depth up to L |
| 4 | + |
| 5 | +from typing import List |
| 6 | + |
| 7 | + |
| 8 | +class TrieNode: |
| 9 | + |
| 10 | + def __init__(self): |
| 11 | + self.children = {} |
| 12 | + self.word = None |
| 13 | + |
| 14 | + |
| 15 | +class Solution: |
| 16 | + |
| 17 | + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: |
| 18 | + root = TrieNode() |
| 19 | + for word in words: |
| 20 | + node = root |
| 21 | + for char in word: |
| 22 | + if char not in node.children: |
| 23 | + node.children[char] = TrieNode() |
| 24 | + node = node.children[char] |
| 25 | + node.word = word |
| 26 | + |
| 27 | + rows, cols = len(board), len(board[0]) |
| 28 | + result = [] |
| 29 | + |
| 30 | + def dfs(r: int, c: int, parent: TrieNode): |
| 31 | + char = board[r][c] |
| 32 | + curr_node = parent.children.get(char) |
| 33 | + if not curr_node: |
| 34 | + return |
| 35 | + |
| 36 | + if curr_node.word: |
| 37 | + result.append(curr_node.word) |
| 38 | + curr_node.word = None |
| 39 | + |
| 40 | + board[r][c] = "#" # mark visited |
| 41 | + |
| 42 | + for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): |
| 43 | + nr, nc = r + dr, c + dc |
| 44 | + if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#": |
| 45 | + if board[nr][nc] in curr_node.children: |
| 46 | + dfs(nr, nc, curr_node) |
| 47 | + |
| 48 | + board[r][c] = char # backtrack |
| 49 | + |
| 50 | + # Prune leaf nodes to accelerate search |
| 51 | + if not curr_node.children: |
| 52 | + del parent.children[char] |
| 53 | + |
| 54 | + for r in range(rows): |
| 55 | + for c in range(cols): |
| 56 | + if board[r][c] in root.children: |
| 57 | + dfs(r, c, root) |
| 58 | + |
| 59 | + return result |
0 commit comments