|
| 1 | +class TrieNode: |
| 2 | + def __init__(self): |
| 3 | + self.children = {} # ํ์ฌ ๋ฌธ์์์ ๊ฐ ์ ์๋ ๋ค์ ๋ฌธ์๋ค ์ ์ฅ |
| 4 | + self.word = None # ์ด๋
ธ๋์์ ๋๋๋ ๋จ์ด๊ฐ ์๋ค๋ฉด ์ ์ฅ |
| 5 | + |
| 6 | +class Solution: |
| 7 | + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: |
| 8 | + |
| 9 | + # ๋ค์ํ์ด๋ณผ๊ฒ. ์ด๋ ค์ ์. Trie! ๋ณด๋๋ก ํ์ํด์ผํจ!(๋จ์ด๋ก ํ์ํ๋๊ฒ ์๋!) |
| 10 | + # DFS(๋ฐฑํธ๋ํน), trie |
| 11 | + # DFS๋ก๋ง ํ๋ฉด TLE(์๊ฐ์ด๊ณผ)๋ธ. trie๊ตฌ์กฐ๋ฅผ ์ด์ฉํด์ผํจ. |
| 12 | + |
| 13 | + # Trie๋ฃจํธ๋
ธ๋ ์์ฑ |
| 14 | + root = TrieNode() |
| 15 | + |
| 16 | + # words ๋ฆฌ์คํธ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก Trie ์์ฑ |
| 17 | + for word in words: |
| 18 | + node = root |
| 19 | + |
| 20 | + for i in word: |
| 21 | + |
| 22 | + if i not in node.children: |
| 23 | + node.children[i] = TrieNode() |
| 24 | + node = node.children[i] |
| 25 | + |
| 26 | + node.word = word # ๋จ์ด ๋์์ word ์ ์ฅ |
| 27 | + |
| 28 | + answer = [] |
| 29 | + |
| 30 | + rows, cols = len(board), len(board[0]) |
| 31 | + |
| 32 | + # DFS |
| 33 | + def dfs(x, y, node): |
| 34 | + c = board[x][y] |
| 35 | + |
| 36 | + # ํ์ฌ ๋ฌธ์๊ฐ ํธ๋ผ์ด์ ์์ผ๋ฉด ๋ฐ๋ก ์ข
๋ฃ |
| 37 | + if c not in node.children: |
| 38 | + return |
| 39 | + |
| 40 | + next_node = node.children[c] |
| 41 | + |
| 42 | + # ๋จ์ด๋ฅผ ์ฐพ์ผ๋ฉด answer์ ์ถ๊ฐํ๊ณ , ์ค๋ณต๋ฐฉ์ง์ํด None์ฒ๋ฆฌ |
| 43 | + if next_node.word: |
| 44 | + answer.append(next_node.word) |
| 45 | + next_node.word = None # ์ค๋ณต๋ฐฉ์ง |
| 46 | + |
| 47 | + board[x][y] = '#' # ํ์ฌ์์น '#'๋ก ๋ฐฉ๋ฌธํ์ |
| 48 | + |
| 49 | + # ์ํ์ข์ฐ DFS ํ์ |
| 50 | + for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]: |
| 51 | + nx, ny = x + dx, y + dy |
| 52 | + # ๋ฒ์ ๋ด์ ์๊ณ , ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์์น๋ผ๋ฉด DFS ํ์ |
| 53 | + if 0 <= nx < rows and 0 <= ny < cols and board[nx][ny] != '#': |
| 54 | + dfs(nx, ny, next_node) |
| 55 | + |
| 56 | + # DFS ์ข
๋ฃ ํ, ์๋ ๋ฌธ์๋ก ๋ณต๊ตฌ(๋ฐฑํธ๋ํน) |
| 57 | + board[x][y] = c # ์์๋ณต๊ตฌ |
| 58 | + |
| 59 | + |
| 60 | + # DFS ์์์ (๋ชจ๋ ๋ณด๋ ์นธ์ ์์์ ์ผ๋ก DFS ํ์) |
| 61 | + for i in range(rows): |
| 62 | + for j in range(cols): |
| 63 | + dfs(i, j, root) |
| 64 | + |
| 65 | + return answer |
0 commit comments