Skip to content

Commit 4da6e92

Browse files
committed
feat: Solve word-search-ii problem
1 parent 5ff8112 commit 4da6e92

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

word-search-ii/hu6r1s.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
3+
n, m = len(board), len(board[0])
4+
res = set()
5+
6+
trie = {}
7+
for word in words:
8+
node = trie
9+
for ch in word:
10+
node = node.setdefault(ch, {})
11+
node['$'] = word
12+
13+
def dfs(x, y, node):
14+
ch = board[x][y]
15+
if ch not in node:
16+
return
17+
nxt = node[ch]
18+
19+
if '$' in nxt:
20+
res.add(nxt['$'])
21+
22+
board[x][y] = "#"
23+
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
24+
nx, ny = x + dx, y + dy
25+
if 0 <= nx < n and 0 <= ny < m and board[nx][ny] != "#":
26+
dfs(nx, ny, nxt)
27+
board[x][y] = ch
28+
29+
for i in range(n):
30+
for j in range(m):
31+
dfs(i, j, trie)
32+
33+
return list(res)

0 commit comments

Comments
 (0)