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
|
class Solution:
def hasPath(self , matrix , word):
# write code here
result = False
def backtrack(state, matrix, word):
if len(state) == len(word):
nonlocal result
result = True
return
if len(state) == 0:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == word[0]:
next_state = list(state)
next_state.append((i, j))
backtrack(next_state, matrix, word)
else:
# up
i, j = state[-1]
if i - 1 >=0 and (i - 1, j) not in state:
if matrix[i - 1][j] == word[len(state)]:
next_state = list(state)
next_state.append((i - 1, j))
backtrack(next_state, matrix, word)
# right
if j + 1 < len(matrix[0]) and (i, j + 1) not in state:
if matrix[i][j + 1] == word[len(state)]:
next_state = list(state)
next_state.append((i, j + 1))
backtrack(next_state, matrix, word)
# left
if j - 1 >=0 and (i, j - 1) not in state:
if matrix[i][j - 1] == word[len(state)]:
next_state = list(state)
next_state.append((i, j - 1))
backtrack(next_state, matrix, word)
# down
if i + 1 < len(matrix) and (i + 1, j) not in state:
if matrix[i + 1][j] == word[len(state)]:
next_state = list(state)
next_state.append((i + 1, j))
backtrack(next_state, matrix, word)
backtrack([], matrix, word)
return result
|