-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path79_word_search.py
36 lines (28 loc) · 949 Bytes
/
79_word_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])
path = set()
def dfs(r, c, i):
if i == len(word):
return True
if (r < 0
or c < 0
or c >= cols
or r >= rows
or word[i] != board[r][c]
or (r, c) in path):
return False
path.add((r, c))
res = (dfs(r + 1, c, i + 1)
or dfs(r - 1, c, i + 1)
or dfs(r, c + 1, i + 1)
or dfs(r, c - 1, i + 1))
path.remove((r, c))
return res
for r in range(rows):
for c in range(cols):
if dfs(r, c, 0):
return True
return False
# Time Complexity O(m * n * 4^l) where l is the word's length
# Space Complexity O(l)