Skip to content
BytePatterns

Landlocked Islands

MediumMatrix & Grid#flood-fill#grid-traversal~30m

Problem

A map is a grid of 1s for land and 0s for water, and an island is a group of land cells joined up, down, left or right. Count the islands that are completely surrounded by water inside the map, meaning no cell of the island lies in the first or last row or column. Islands that touch the edge might continue off the map, so they do not count. The grid may be empty.

Examples

Input:  grid = [[1, 1, 0, 0, 0],
                [1, 0, 0, 1, 0],
                [0, 0, 1, 1, 0],
                [0, 0, 0, 0, 0],
                [0, 1, 0, 0, 1]]
Output: 1
Why:    only the three cells in the middle stay clear of the edge
Input:  grid = [[0, 0, 0],
                [0, 1, 0],
                [0, 0, 0]]
Output: 1
Why:    a single inland cell is an island
Input:  grid = [[1]]
Output: 0
Why:    edge case, the only cell lies on the edge

Hints

0 / 3

Stuck on the idea rather than the code? Number of Islands covers it.