Skip to content

Commit 864779b

Browse files
committed
79
1 parent f1a79ab commit 864779b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

word-search/jeldo.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
# (O(m*n))
3+
def exist(self, board: List[List[str]], word: str) -> bool:
4+
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
5+
result = False
6+
7+
def dfs(i, j, visited, w):
8+
nonlocal result
9+
if (i, j) in visited:
10+
return
11+
if not (0 <= i < len(board)) or not (0 <= j < len(board[0])):
12+
return
13+
w += board[i][j]
14+
if not (word[:len(w)] == w):
15+
return
16+
visited.add((i, j))
17+
if w == word:
18+
result = True
19+
return
20+
for d in dirs:
21+
dfs(i + d[0], j + d[1], visited, w)
22+
visited.remove((i, j)) # backtracking
23+
24+
for i in range(len(board)):
25+
for j in range(len(board[0])):
26+
dfs(i, j, set(), "")
27+
if result:
28+
return True
29+
return False

0 commit comments

Comments
 (0)