##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1391.html

# 1391. Check if There is a Valid Path in a Grid (Medium)

Given a m x n grid. Each cell of the 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 which 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.

Example 1:

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).


Example 2:

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)


Example 3:

Input: grid = [[1,1,2]]
Output: false
Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).


Example 4:

Input: grid = [[1,1,1,1,1,1,3]]
Output: true


Example 5:

Input: grid = [[2],[2],[2],[2],[2],[2],[6]]
Output: true


Constraints:

• m == grid.length
• n == grid[i].length
• 1 <= m, n <= 300
• 1 <= grid[i][j] <= 6

Related Topics: Depth-first Search, Breadth-first Search

## Solution 1. Union Find

// OJ: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/
// Time: O(MN)
// Space: O(MN)
class UnionFind {
private:
vector<int> id, rank;
int find (int i) {
if (id[i] == i) return i;
return id[i] = find(id[i]);
}
public:
UnionFind(int n) : id(n), rank(n, 0) {
for (int i = 0; i < n; ++i) id[i] = i;
}
void connect(int i, int j) {
int p = find(i), q = find(j);
if (p == q) return;
if (rank[p] > rank[q]) id[p] = q;
else {
id[q] = p;
if (rank[p] == rank[q]) rank[p]++;
}
}
bool connected(int i, int j) { return find(i) == find(j); }
};
class Solution {
int M, N;
int h(int x, int y) { return x * N + y; }
const int dirs[4][2] = { {0,-1},{0,1},{-1,0},{1,0} };
const int neighbor[6][2] = { {0,1}, {2,3}, {0,3}, {1,3}, {0,2}, {1,2} };
public:
bool hasValidPath(vector<vector<int>>& A) {
M = A.size(), N = A[0].size();
UnionFind uf(M * N);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
for (int n : neighbor[A[i][j] - 1]) {
int x = i + dirs[n][0], y = j + dirs[n][1];
if (x < 0 || x >= M || y < 0 || y >= N) continue;
int r = n ^ 1;
auto &rn = neighbor[A[x][y] - 1];
if (rn[0] != r && rn[1] != r) continue;
uf.connect(h(x, y), h(i, j));
}
}
}
return uf.connected(h(0,0), h(M-1,N-1));
}
};


## Solution 2. DFS

// OJ: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/
// Time: O(MN)
// Space: O(MN)
class Solution {
int M, N;
vector<vector<int>> A;
vector<vector<bool>> vis;
int h(int x, int y) { return x * N + y; }
int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1}, t[6] = {4|8, 1|2, 8|1, 4|1, 8|2, 4|2};
bool dfs(int i, int j) {
if (i == M - 1 && j == N - 1) return 1;
vis[i][j] = 1;
for (int k = 0; k < 4; ++k) {
if (t[A[i][j] - 1] >> k & 1 ^ 1) continue; // If A[i][j] can't extend to this direction, skip
int x = i + dx[k], y = j + dy[k];
if (x < 0 || x >= M || y < 0 || y >= N || vis[x][y]) continue;
int rk = k ^ 1;
if (t[A[x][y] - 1] >> rk & 1 ^ 1) continue; // If A[x][y] can't extend back, skip
if (dfs(x, y)) return 1;
}
return 0;
}
public:
bool hasValidPath(vector<vector<int>>& A) {
M = A.size(), N = A[0].size();
this->A = A;
vis.assign(M, vector<bool>(N));
return dfs(0, 0);
}
};

• class Solution {
public boolean hasValidPath(int[][] grid) {
int rows = grid.length, columns = grid[0].length;
boolean[][] visited = new boolean[rows][columns];
visited[0][0] = true;
queue.offer(new int[]{0, 0});
while (!queue.isEmpty()) {
int[] cell = queue.poll();
if (cell[0] == rows - 1 && cell[1] == columns - 1)
return true;
List<int[]> reachableCells = reachableCells(grid[cell[0]][cell[1]], grid, cell, rows, columns);
for (int[] reachableCell : reachableCells) {
int row = reachableCell[0], column = reachableCell[1];
if (!visited[row][column]) {
visited[row][column] = true;
queue.offer(new int[]{row, column});
}
}
}
return false;
}

public List<int[]> reachableCells(int street, int[][] grid, int[] cell, int rows, int columns) {
List<int[]> reachableCells = new ArrayList<int[]>();
int row = cell[0], column = cell[1];
if (street == 1) {
int newColumn1 = column - 1, newColumn2 = column + 1;
if (newColumn1 >= 0) {
int newStreet = grid[row][newColumn1];
if (newStreet == 1 || newStreet == 4 || newStreet == 6)
}
if (newColumn2 < columns) {
int newStreet = grid[row][newColumn2];
if (newStreet == 1 || newStreet == 3 || newStreet == 5)
}
} else if (street == 2) {
int newRow1 = row - 1, newRow2 = row + 1;
if (newRow1 >= 0) {
int newStreet = grid[newRow1][column];
if (newStreet == 2 || newStreet == 3 || newStreet == 4)
}
if (newRow2 < rows) {
int newStreet = grid[newRow2][column];
if (newStreet == 2 || newStreet == 5 || newStreet == 6)
}
} else if (street == 3) {
int newRow = row + 1, newColumn = column - 1;
if (newRow < rows) {
int newStreet = grid[newRow][column];
if (newStreet == 2 || newStreet == 5 || newStreet == 6)
}
if (newColumn >= 0) {
int newStreet = grid[row][newColumn];
if (newStreet == 1 || newStreet == 4 || newStreet == 6)
}
} else if (street == 4) {
int newRow = row + 1, newColumn = column + 1;
if (newRow < rows) {
int newStreet = grid[newRow][column];
if (newStreet == 2 || newStreet == 5 || newStreet == 6)
}
if (newColumn < columns) {
int newStreet = grid[row][newColumn];
if (newStreet == 1 || newStreet == 3 || newStreet == 5)
}
} else if (street == 5) {
int newRow = row - 1, newColumn = column - 1;
if (newRow >= 0) {
int newStreet = grid[newRow][column];
if (newStreet == 2 || newStreet == 3 || newStreet == 4)
}
if (newColumn >= 0) {
int newStreet = grid[row][newColumn];
if (newStreet == 1 || newStreet == 4 || newStreet == 6)
}
} else if (street == 6) {
int newRow = row - 1, newColumn = column + 1;
if (newRow >= 0) {
int newStreet = grid[newRow][column];
if (newStreet == 2 || newStreet == 3 || newStreet == 4)
}
if (newColumn < columns) {
int newStreet = grid[row][newColumn];
if (newStreet == 1 || newStreet == 3 || newStreet == 5)
}
}
return reachableCells;
}
}

############

class Solution {
private int[] p;
private int[][] grid;
private int m;
private int n;

public boolean hasValidPath(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
p = new int[m * n];
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int e = grid[i][j];
if (e == 1) {
left(i, j);
right(i, j);
} else if (e == 2) {
up(i, j);
down(i, j);
} else if (e == 3) {
left(i, j);
down(i, j);
} else if (e == 4) {
right(i, j);
down(i, j);
} else if (e == 5) {
left(i, j);
up(i, j);
} else {
right(i, j);
up(i, j);
}
}
}
return find(0) == find(m * n - 1);
}

private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}

private void left(int i, int j) {
if (j > 0 && (grid[i][j - 1] == 1 || grid[i][j - 1] == 4 || grid[i][j - 1] == 6)) {
p[find(i * n + j)] = find(i * n + j - 1);
}
}

private void right(int i, int j) {
if (j < n - 1 && (grid[i][j + 1] == 1 || grid[i][j + 1] == 3 || grid[i][j + 1] == 5)) {
p[find(i * n + j)] = find(i * n + j + 1);
}
}

private void up(int i, int j) {
if (i > 0 && (grid[i - 1][j] == 2 || grid[i - 1][j] == 3 || grid[i - 1][j] == 4)) {
p[find(i * n + j)] = find((i - 1) * n + j);
}
}

private void down(int i, int j) {
if (i < m - 1 && (grid[i + 1][j] == 2 || grid[i + 1][j] == 5 || grid[i + 1][j] == 6)) {
p[find(i * n + j)] = find((i + 1) * n + j);
}
}
}

• // OJ: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/
// Time: O(MN)
// Space: O(MN)
class UnionFind {
private:
vector<int> id, rank;
int find (int i) {
if (id[i] == i) return i;
return id[i] = find(id[i]);
}
public:
UnionFind(int n) : id(n), rank(n, 0) {
for (int i = 0; i < n; ++i) id[i] = i;
}
void connect(int i, int j) {
int p = find(i), q = find(j);
if (p == q) return;
if (rank[p] > rank[q]) id[p] = q;
else {
id[q] = p;
if (rank[p] == rank[q]) rank[p]++;
}
}
bool connected(int i, int j) { return find(i) == find(j); }
};
class Solution {
int M, N;
int h(int x, int y) { return x * N + y; }
const int dirs[4][2] = { {0,-1},{0,1},{-1,0},{1,0} };
const int neighbor[6][2] = { {0,1}, {2,3}, {0,3}, {1,3}, {0,2}, {1,2} };
public:
bool hasValidPath(vector<vector<int>>& A) {
M = A.size(), N = A[0].size();
UnionFind uf(M * N);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
for (int n : neighbor[A[i][j] - 1]) {
int x = i + dirs[n][0], y = j + dirs[n][1];
if (x < 0 || x >= M || y < 0 || y >= N) continue;
int r = n ^ 1;
auto &rn = neighbor[A[x][y] - 1];
if (rn[0] != r && rn[1] != r) continue;
uf.connect(h(x, y), h(i, j));
}
}
}
return uf.connected(h(0,0), h(M-1,N-1));
}
};

• class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
p = list(range(m * n))

def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]

def left(i, j):
if j > 0 and grid[i][j - 1] in (1, 4, 6):
p[find(i * n + j)] = find(i * n + j - 1)

def right(i, j):
if j < n - 1 and grid[i][j + 1] in (1, 3, 5):
p[find(i * n + j)] = find(i * n + j + 1)

def up(i, j):
if i > 0 and grid[i - 1][j] in (2, 3, 4):
p[find(i * n + j)] = find((i - 1) * n + j)

def down(i, j):
if i < m - 1 and grid[i + 1][j] in (2, 5, 6):
p[find(i * n + j)] = find((i + 1) * n + j)

for i in range(m):
for j in range(n):
e = grid[i][j]
if e == 1:
left(i, j)
right(i, j)
elif e == 2:
up(i, j)
down(i, j)
elif e == 3:
left(i, j)
down(i, j)
elif e == 4:
right(i, j)
down(i, j)
elif e == 5:
left(i, j)
up(i, j)
else:
right(i, j)
up(i, j)
return find(0) == find(m * n - 1)


• func hasValidPath(grid [][]int) bool {
m, n := len(grid), len(grid[0])
p := make([]int, m*n)
for i := range p {
p[i] = i
}
var find func(x int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
left := func(i, j int) {
if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) {
p[find(i*n+j)] = find(i*n + j - 1)
}
}
right := func(i, j int) {
if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) {
p[find(i*n+j)] = find(i*n + j + 1)
}
}
up := func(i, j int) {
if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) {
p[find(i*n+j)] = find((i-1)*n + j)
}
}
down := func(i, j int) {
if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) {
p[find(i*n+j)] = find((i+1)*n + j)
}
}
for i, row := range grid {
for j, e := range row {
if e == 1 {
left(i, j)
right(i, j)
} else if e == 2 {
up(i, j)
down(i, j)
} else if e == 3 {
left(i, j)
down(i, j)
} else if e == 4 {
right(i, j)
down(i, j)
} else if e == 5 {
left(i, j)
up(i, j)
} else {
right(i, j)
up(i, j)
}
}
}
return find(0) == find(m*n-1)
}