Given a m x ngrid
. 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
Solution: BFS
Need to check both sides (x, y) -> (tx, ty) and (tx, ty) -> (x, y) to make sure a path exist.
Time complexity: O(m*n)
Space complexity: O(m*n)
C++
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 |
// Author: Huahua class Solution { public: bool hasValidPath(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); vector<int> dirs{0, -1, 0, 1, 0}; // [up, left, down, right] vector<set<int>> rules{ {1, 3}, {0, 2}, {1, 2}, {2, 3}, {0, 1}, {0, 3}}; queue<int> q{{0}}; vector<int> seen(m * n); seen[0] = 1; while (!q.empty()) { int cx = q.front() % n; int cy = q.front() / n; q.pop(); if (cx == n - 1 && cy == m - 1) return true; for (int d : rules[grid[cy][cx] - 1]) { int x = cx + dirs[d]; int y = cy + dirs[d + 1]; int key = y * n + x; if (x < 0 || x >= n || y < 0 || y >= m || seen[key] || !rules[grid[y][x] - 1].count((d + 2) % 4)) continue; seen[key] = 1; q.push(key); } } return false; } }; |