-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path79_Word_Search.py
More file actions
35 lines (28 loc) · 912 Bytes
/
Copy path79_Word_Search.py
File metadata and controls
35 lines (28 loc) · 912 Bytes
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
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROWS, COLS = len(board), len(board[0])
def dfs(r: int, c: int, i: int) -> bool:
if i == len(word):
return True
if (
r < 0 or c < 0 or
r >= ROWS or c >= COLS or
board[r][c] != word[i] or
board[r][c] == "#"
):
return False
temp = board[r][c]
board[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)
)
board[r][c] = temp
return res
for r in range(ROWS):
for c in range(COLS):
if dfs(r, c, 0):
return True
return False