Skip to content

Commit 0cc1d29

Browse files
committed
solve: wordSearchIi
1 parent c8d1ff9 commit 0cc1d29

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

word-search-ii/yolophg.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time Complexity: O(m * n * 4^l) -> each cell can explore up to 4 directions recursively, where l is the max word length.
2+
# Space Complexity: O(w * l) -> storing words in a dictionary-based Trie.
3+
4+
class Solution:
5+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
6+
# trie-like dictionary to store words
7+
d = {}
8+
9+
# build the trie
10+
for word in words:
11+
cur = d
12+
for c in word:
13+
if c not in cur:
14+
# create a new node
15+
cur[c] = {}
16+
cur = cur[c]
17+
# mark the end of the word
18+
cur["*"] = word
19+
20+
# right, down, up, left
21+
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
22+
23+
# backtracking function
24+
def dfs(i, j, cur, seen):
25+
result = set()
26+
if "*" in cur:
27+
# found a word, add it
28+
result = {cur["*"]}
29+
30+
for x, y in directions:
31+
ni, nj = i + x, j + y
32+
if 0 <= ni < len(board) and 0 <= nj < len(board[0]) and (ni, nj) not in seen and board[ni][nj] in cur:
33+
result.update(dfs(ni, nj, cur[board[ni][nj]], seen | {(ni, nj)}))
34+
35+
return result
36+
37+
result = set()
38+
39+
# start dfs search from every cell in the board
40+
for i in range(len(board)):
41+
for j in range(len(board[0])):
42+
if board[i][j] in d:
43+
result.update(dfs(i, j, d[board[i][j]], {(i, j)}))
44+
45+
return list(result)

0 commit comments

Comments
 (0)