Skip to content

Commit 8dbfe7e

Browse files
committed
solve 5
1 parent 65b2b95 commit 8dbfe7e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

word-search-ii/pmjuu.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
시간 복잡도: O(m * n * 4^s) s = word 최대 길이
3+
공간 복잡도: O(w) w = 모든 단어에 포함된 문자 수의 합
4+
'''
5+
from typing import List
6+
7+
class Solution:
8+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
9+
root = {}
10+
for word in words:
11+
node = root
12+
13+
for char in word:
14+
if char not in node:
15+
node[char] = {}
16+
node = node[char]
17+
18+
node['$'] = word
19+
20+
def dfs(i, j, node, visited):
21+
if '$' in node:
22+
result.append(node['$'])
23+
del node['$']
24+
25+
if not (0 <= i < m and 0 <= j < n) or (i, j) in visited:
26+
return
27+
28+
char = board[i][j]
29+
if char not in node:
30+
return
31+
32+
visited.add((i, j))
33+
34+
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
35+
dfs(i + di, j + dj, node[char], visited)
36+
37+
visited.remove((i, j))
38+
39+
m, n = len(board), len(board[0])
40+
result = []
41+
42+
for i in range(m):
43+
for j in range(n):
44+
dfs(i, j, root, set())
45+
46+
return result

0 commit comments

Comments
 (0)