Katkat

Count Four-Neighbor Islands in a Binary Matrix

AmazonSoftware Engineer · Online Assessment

Last updated

Count four-neighbor islands in a binary matrix and consider the connectivity state needed when rows arrive as a stream.

Given a two-dimensional binary matrix, return the number of islands. An island is a connected component of cells containing 1. Cells connect only through a shared edge: up, down, left, or right. Diagonal contact does not connect islands.

Input and Output

  • Input: a rectangular matrix containing only 0 and 1.
  • Output: one integer, the number of islands.
  • For this practice version, an empty matrix or a matrix with no land has answer 0.

Example

grid = [
 [1, 1, 0],
 [0, 1, 0],
 [1, 0, 1]
]
answer = 3

The connected cells at the upper left form one island; the two isolated cells in the last row form two more.

Discussion Extension

How would the task change if matrix rows arrived one at a time? The source asks this as a follow-up but supplies no streaming-call interface; the function above receives the complete matrix.