-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0079-word-search.py
49 lines (38 loc) · 1.29 KB
/
0079-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
37
38
39
40
41
42
43
44
45
46
47
48
49
from collections import deque
class Solution:
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
ans = False
def backtracking(self, x, y, cnt = 0):
if self.ans:
return
if cnt == len(self.word):
self.ans = True
return
for i in range(4):
nx, ny = x + self.dx[i], y + self.dy[i]
if nx < 0 or nx >= self.n or ny < 0 or ny >= self.m or self.vst[nx][ny]:
continue
if self.word[cnt] != self.board[nx][ny]:
continue
self.vst[nx][ny] = True
self.backtracking(nx, ny, cnt + 1)
self.vst[nx][ny] = False
def exist(self, board: List[List[str]], word: str) -> bool:
self.n, self.m = len(board), len(board[0])
self.word = word
self.vst = [[False] * self.m for _ in range(self.n)]
self.board = board
d = deque()
for i in range(self.n):
for j in range(self.m):
if word[0] == board[i][j]:
d.append([i, j, 1])
while d:
x, y, cnt = d.pop()
self.vst[x][y] = True
self.backtracking(x, y, cnt)
self.vst[x][y] = False
if self.ans:
return True
return False