Check if There is a Valid Path in a Grid - Problem
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.
Input & Output
Example 1 — Valid Path Exists
$
Input:
grid = [[2,4,3],[6,5,2]]
›
Output:
true
💡 Note:
Path exists: (0,0) → (1,0) → (1,1) → (1,2). Street 2 at (0,0) connects down to street 6 at (1,0), which connects up. Then street 6 connects right to street 5 at (1,1), and so on.
Example 2 — No Valid Path
$
Input:
grid = [[1,2,1],[1,2,1]]
›
Output:
false
💡 Note:
Street 1 at (0,0) only connects left-right, but there's no valid connection downward. Street 2 at (0,1) connects up-down but (0,0) doesn't connect right.
Example 3 — Single Cell
$
Input:
grid = [[6]]
›
Output:
true
💡 Note:
Start and end are the same cell (0,0), so the path is valid by default.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 300
- 1 ≤ grid[i][j] ≤ 6
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
Each number represents a street type with specific connections
2
Validate Connections
Check if adjacent cells can connect to each other
3
Find Path
Use DFS/BFS to find valid route from (0,0) to bottom-right
Key Takeaway
🎯 Key Insight: Street connections must be bidirectional - both cells must connect to each other for valid movement
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code