philosyang.com

212. Word Search II

If they ask this one tmr i’m killin it

 1class Trie:
 2
 3    def __init__(self):
 4        self.root = {}
 5
 6    def insert(self, word: str) -> None:
 7        node = self.root
 8        for ch in word:
 9            if ch not in node:
10                node[ch] = {}
11            node = node[ch]
12        node["word"] = word
13
14
15class Solution:
16    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
17        trie = Trie()
18        for word in words:
19            trie.insert(word)
20
21        dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
22        m, n = len(board), len(board[0])
23        result = set()
24
25        def dfs(x: int, y: int, node: dict) -> None:
26            ch = board[x][y]
27            if ch not in node:
28                return
29
30            node = node[ch]
31            if "word" in node:
32                result.add(node["word"])
33
34            board[x][y] = "#"  # visited
35            for dx, dy in dirs:
36                nx, ny = x + dx, y + dy
37                if 0 <= nx < m and 0 <= ny < n:
38                    dfs(nx, ny, node)
39            board[x][y] = ch  # un-visit
40
41            return
42
43        for i in range(m):
44            for j in range(n):
45                dfs(i, j, trie.root)
46
47        return list(result)

#Array #String #Backtracking #Trie #Matrix #Python #Revisit