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
Valid Path in Grid - DFS Approach INPUT 2x3 Grid with Street Types 2 4 3 6 5 2 S E Street Types: 1: L-R 2: U-D 3: L-D 4: R-D 5: L-U 6: R-U grid = [[2,4,3], [6,5,2]] ALGORITHM (DFS) 1 Start at (0,0) Mark visited, check type=2 2 Check Connections Type 2 connects U-D only 3 Traverse Valid Paths Recursive DFS exploration 4 Reach Target Check if (m-1,n-1) reached DFS Path Trace: (0,0) (1,0) (1,1) (1,2) Path Found: 4 cells visited (0,0)-->(1,0)-->(1,1)-->(1,2) FINAL RESULT Valid Path Exists! S E Output: true Status: OK Path connects (0,0) to (1,2) successfully Time: O(m*n) Space: O(m*n) Key Insight: Each street type defines exactly 2 directions it connects. For DFS to move between cells, both the current cell must have an exit in that direction AND the neighbor cell must have an entrance from that direction. This bidirectional validation ensures valid street connections. TutorialsPoint - Check if There is a Valid Path in a Grid | DFS Approach
Asked in
Google 12 Facebook 8 Amazon 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen