Check if There is a Valid Path in a Grid LeetCode solution in Python
1class Solution:2def hasValidPath(self, grid: List[List[int]]) -> bool:3r, c = len(grid), len(grid[0])4dic = {52: [(-1, 0), (1, 0)],61: [(0, 1), (0, -1)],75: [(-1, 0), (0, -1)],83: [(1, 0), (0, -1)],96: [(0, 1), (-1, 0)],104: [(0, 1), (1, 0)],11}12q = collections.deque([(0, 0)])13visit = set()14while q:15i, j = q.popleft()16visit.add((i, j))17if i == r - 1 and j == c - 1:18return True19for x, y in dic[grid[i][j]]:20nx = i + x21ny = j + y22if nx >= 0 and nx < r and ny >= 0 and ny < c and (nx, ny) not in visit:23if (-x, -y) in dic[grid[nx][ny]]:24q.append((nx, ny))25return False