-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path79_Word_Search.py
More file actions
40 lines (28 loc) · 1.11 KB
/
79_Word_Search.py
File metadata and controls
40 lines (28 loc) · 1.11 KB
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
37
38
39
40
# 1 Possible Solutions
# 1. DFS + Graph
class Solution:
# Time: O(M*N*3^L), Space: O(L)
def exist(self, board: List[List[str]], word: str) -> bool:
if not board:
return False
if not word:
return False
rows, cols = len(board), len(board[0])
visited = set()
def dfs(row, col, idx):
if idx == len(word):
return True
if row < 0 or row >= rows or col < 0 or col >= cols or word[idx] != board[row][col] or (row, col) in visited:
return False
visited.add((row, col))
result = (dfs(row + 1, col, idx + 1) or
dfs(row - 1, col, idx + 1) or
dfs(row, col + 1, idx + 1) or
dfs(row, col - 1, idx + 1 ))
visited.remove((row, col))
return result
for row in range(rows):
for col in range(cols):
if dfs(row, col, 0):
return True
return False