Count Four-Neighbor Islands in a Binary Matrix
AmazonSoftware Engineer · Online AssessmentLast 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
0and1. - 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.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.