FastPrepBinary Matrix Top-to-Bottom Reachability
Problem · Matrix

Binary Matrix Top-to-Bottom Reachability

Learn this problem
MediumGoogle logoGoogleFULLTIMEONSITE INTERVIEW
See Google hiring insights

Problem 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[][]) → boolean

Examples

Example 1

grid = [[0,1,1],[0,0,1],[1,0,0]]return = true

One 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 = false

The blocked middle row separates every open top-row cell from the bottom row.

Example 3

grid = [[1,0,1]]return = true

The only row is both the top and bottom row. Its open cell is already a valid destination.

Constraints

  • 1 <= grid.length <= 500
  • 1 <= grid[i].length <= 500
  • Every row has the same length.
  • Every cell is either 0 or 1.
  • A move changes the row or column by exactly 1, but not both.

More Google problems

drafts saved locally
public boolean canReachBottom(int[][] grid) {
    // Write your code here.
}
grid[[0,1,1],[0,0,1],[1,0,0]]
expectedtrue
checking account