1391. Check if There is a Valid Path in a Grid
https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/

Last updated
https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/

Last updated
Input: grid = [[2,4,3],[6,5,2]]
Output: true
Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).Input: grid = [[1,2,1],[1,2,1]]
Output: false
Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)Input: grid = [[1,1,2]]
Output: false
Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).Input: grid = [[1,1,1,1,1,1,3]]
Output: trueInput: grid = [[2],[2],[2],[2],[2],[2],[6]]
Output: trueclass Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
m = len(grid)
n = len(grid[0])
v = [[False] * n for i in range(m)]
dirs = [[(0, -1), (0, 1)],
[(-1, 0), (1, 0)],
[(0, -1), (1, 0)],
[(1, 0), (0, 1)],
[(-1, 0), (0, -1)],
[(-1, 0), (0, 1)]]
q = [(0, 0)]
v[0][0] = True
while len(q) != 0:
t = q[0]
q.pop(0)
for _, d in enumerate(dirs[grid[t[0]][t[1]] - 1]):
r = t[0] + d[0]
c = t[1] + d[1]
if r >= 0 and r < m and c >= 0 and c < n and not v[r][c]:
for _, nd in enumerate(dirs[grid[r][c] - 1]):
if r + nd[0] == t[0] and c + nd[1] == t[1]:
q.append((r, c))
v[r][c] = True
return v[m - 1][n - 1]