|
| 1 | +from typing import Dict, List |
| 2 | + |
| 3 | + |
| 4 | +class Trie: |
| 5 | + def __init__(self, end: bool = False, letters: Dict[str, "Trie"] = None): |
| 6 | + self.end = end |
| 7 | + self.children = letters if letters is not None else {} |
| 8 | + |
| 9 | + def insert(self, word: str) -> None: |
| 10 | + parent = self |
| 11 | + for c in word: |
| 12 | + if c not in parent.children: |
| 13 | + parent.children[c] = Trie() |
| 14 | + parent = parent.children[c] |
| 15 | + parent.end = True |
| 16 | + |
| 17 | + |
| 18 | +class Solution: |
| 19 | + """Base class for all LeetCode Problems.""" |
| 20 | + |
| 21 | + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: |
| 22 | + """ |
| 23 | + Given an m x n board of characters and a list of strings words, return all words |
| 24 | + on the board. |
| 25 | +
|
| 26 | + Each word must be constructed from letters of sequentially adjacent cells, |
| 27 | + where adjacent cells are horizontally or vertically neighboring. The same |
| 28 | + letter cell may not be used more than once in a word. |
| 29 | + """ |
| 30 | + |
| 31 | + root = Trie() |
| 32 | + for word in words: |
| 33 | + root.insert(word) |
| 34 | + |
| 35 | + res, path = set(), set() |
| 36 | + |
| 37 | + def dfs(row: int, col: int, node: Trie, word: str): |
| 38 | + if ( |
| 39 | + row < 0 |
| 40 | + or row >= len(board) |
| 41 | + or col < 0 |
| 42 | + or col >= len(board[0]) |
| 43 | + or board[row][col] not in node.children |
| 44 | + or (row, col) in path |
| 45 | + ): |
| 46 | + return False |
| 47 | + path.add((row, col)) |
| 48 | + node = node.children[board[row][col]] |
| 49 | + word += board[row][col] |
| 50 | + if node.end: |
| 51 | + res.add(word) |
| 52 | + dfs(row + 1, col, node, word) |
| 53 | + dfs(row - 1, col, node, word) |
| 54 | + dfs(row, col + 1, node, word) |
| 55 | + dfs(row, col - 1, node, word) |
| 56 | + path.remove((row, col)) |
| 57 | + return res |
| 58 | + |
| 59 | + for row in range(len(board)): |
| 60 | + for col in range(len(board[0])): |
| 61 | + dfs(row, col, root, "") |
| 62 | + return list(res) |
0 commit comments