-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm79.py
30 lines (26 loc) · 1.2 KB
/
m79.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
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
return any(self.searchSpot(board, set([(row, col)]), row, col, word, 0)
for row in range(len(board))
for col in range(len(board[0])))
def searchSpot(self,
board: List[List[str]],
visited: Set[Tuple[int, int]],
row: int,
col: int,
word: str,
indxOfWord: int) -> bool :
output = False
if board[row][col] == word[indxOfWord] :
indxOfWord += 1
if indxOfWord >= len(word) :
return True
nextSpots = [(row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)]
for r, c in nextSpots :
if (0 <= r < len(board)) and (0 <= c < len(board[0])) and (r,c) not in visited :
visited.add((r, c))
output = self.searchSpot(board, visited, r, c, word, indxOfWord)
visited.remove((r, c))
if output :
break
return output