Problem · Matrix
Binary Matrix Top-to-Bottom Reachability
Learn this problemProblem statement
You are given a rectangular binary matrix grid. A cell with value 0 is open, and a cell with value 1 is blocked.
You may start at any open cell in the top row. From an open cell, you may move one cell up, down, left, or right, staying inside the matrix and never entering a blocked cell.
Return true if at least one open cell in the bottom row is reachable from an open cell in the top row. Otherwise, return false.
Function
canReachBottom(grid: int[][]) → booleanExamples
Example 1
grid = [[0,1,1],[0,0,1],[1,0,0]]return = trueOne valid route is (0,0) -> (1,0) -> (1,1) -> (2,1). It reaches an open bottom-row cell.
Example 2
grid = [[0,1,0],[1,1,1],[0,0,0]]return = falseThe blocked middle row separates every open top-row cell from the bottom row.
Example 3
grid = [[1,0,1]]return = trueThe only row is both the top and bottom row. Its open cell is already a valid destination.
Constraints
1 <= grid.length <= 5001 <= grid[i].length <= 500- Every row has the same length.
- Every cell is either
0or1. - A move changes the row or column by exactly
1, but not both.