[LeetCode] Check if There is a Valid Path in a Grid

1391. Check if There is a Valid Path in a Grid

You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:

  • 1 which means a street connecting the left cell and the right cell.
  • 2 which means a street connecting the upper cell and the lower cell.
  • 3 which means a street connecting the left cell and the lower cell.
  • 4 which means a street connecting the right cell and the lower cell.
  • 5 which means a street connecting the left cell and the upper cell.
  • 6 which means a street connecting the right cell and the upper cell.

You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.

Notice that you are not allowed to change any street.

Return true if there is a valid path in the grid or false otherwise.

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
class Solution {
bool validDir(int street, int dir) {
if(street == 1) return dir == 1 or dir == 3;
if(street == 2) return dir == 0 or dir == 2;
if(street == 3) return dir == 2 or dir == 3;
if(street == 4) return dir == 1 or dir == 2;
if(street == 5) return dir == 0 or dir == 3;
if(street == 6) return dir == 0 or dir == 1;

return false;
}
bool connected(int dir, int street2) {
if(dir == 0) return street2 == 2 or street2 == 3 or street2 == 4;
if(dir == 1) return street2 == 1 or street2 == 3 or street2 == 5;
if(dir == 2) return street2 == 2 or street2 == 5 or street2 == 6;
if(dir == 3) return street2 == 1 or street2 == 4 or street2 == 6;

return false;
}
public:
bool hasValidPath(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
vector<vector<int>> vis(n,vector<int>(m));
vis[0][0] = true;
queue<pair<int, int>> q;
q.push({0,0});
int dy[4]={-1,0,1,0}, dx[4]={0,1,0,-1};
while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
for(int dir = 0; dir < 4; dir++) {
if(!validDir(A[y][x], dir)) continue;
int ny = y + dy[dir], nx = x + dx[dir];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx] and connected(dir , A[ny][nx])) {
q.push({ny,nx});
vis[ny][nx] = true;
}
}
}
return vis[n-1][m-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/20/PS/LeetCode/check-if-there-is-a-valid-path-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.