Skip to content

Commit 9cb3659

Browse files
committed
word-search-ii solution
1 parent 6098300 commit 9cb3659

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

โ€Žword-search-ii/yyyyyyyyyKim.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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

Comments
ย (0)