Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e66691e

Browse files
committedSep 7, 2024·
word-search solution
1 parent 405f6e6 commit e66691e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
 

‎word-search/sun912.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
TC: O(ROWS*COLS*4^word length)
3+
SC: O(ROWS*COLS*word length)
4+
"""
5+
6+
class Solution:
7+
def exist(self, board: List[List[str]], word: str) -> bool:
8+
ROWS = len(board)
9+
COLS = len(board[0])
10+
path = set()
11+
12+
def dfs(r,c,i):
13+
if i == len(word):
14+
return True
15+
16+
if (r < 0 or
17+
c < 0 or
18+
r >= ROWS or
19+
c >= COLS or
20+
word[i] != board[r][c] or
21+
(r,c) in path
22+
):
23+
return False
24+
25+
path.add((r,c))
26+
27+
res = (dfs(r+1, c, i+1) or
28+
dfs(r, c+1, i+1) or
29+
dfs(r-1, c, i+1) or
30+
dfs(r, c-1, i+1)
31+
)
32+
path.remove((r,c))
33+
return res
34+
35+
for r in range(ROWS):
36+
for c in range(COLS):
37+
if dfs(r,c, 0): return True
38+
39+
return False
40+
41+

0 commit comments

Comments
 (0)
Please sign in to comment.