-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Search_79.py
More file actions
35 lines (29 loc) · 1.07 KB
/
Word_Search_79.py
File metadata and controls
35 lines (29 loc) · 1.07 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
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
visited = [[False] * (len(board[0])) for _ in range(len(board))]
def isValid(r, c):
if(min(r, c) < 0 or r >= len(board) or c >= len(board[0])):
return False
if(visited[r][c]):
return False
return True
def dfs(r, c, l):
if l == len(word):
return True
if(not isValid(r, c)):
return False
if board[r][c] != word[l]:
return False
visited[r][c] = True
search = ( dfs(r + 1, c, l + 1) or
dfs(r - 1, c, l + 1) or
dfs(r, c + 1, l + 1) or
dfs(r, c - 1, l + 1) )
visited[r][c] = False
return search
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0] and dfs(i, j, 0):
return True
return False