Check if There is a Valid Path in a Grid LeetCode solution in Python

1
class Solution:
2
def hasValidPath(self, grid: List[List[int]]) -> bool:
3
r, c = len(grid), len(grid[0])
4
dic = {
5
2: [(-1, 0), (1, 0)],
6
1: [(0, 1), (0, -1)],
7
5: [(-1, 0), (0, -1)],
8
3: [(1, 0), (0, -1)],
9
6: [(0, 1), (-1, 0)],
10
4: [(0, 1), (1, 0)],
11
}
12
q = collections.deque([(0, 0)])
13
visit = set()
14
while q:
15
i, j = q.popleft()
16
visit.add((i, j))
17
if i == r - 1 and j == c - 1:
18
return True
19
for x, y in dic[grid[i][j]]:
20
nx = i + x
21
ny = j + y
22
if nx >= 0 and nx < r and ny >= 0 and ny < c and (nx, ny) not in visit:
23
if (-x, -y) in dic[grid[nx][ny]]:
24
q.append((nx, ny))
25
return False

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0