Problem 579873 · medium · Level 05 Advanced Algorithms & Graphs

Separate Landmasses on a Sea Chart

graphs · grid · bfs · dfs · flood fill

Grids are graphs in disguise: every cell is a node and its up/down/left/right neighbours are its edges. You never need to build the adjacency list; you compute neighbours on the fly.

A sea chart is an m x n grid of strings: "1" marks land and "0" marks sea. Land cells that share a side (up, down, left or right; touching corners do not count) belong to the same island, and everything beyond the chart's border is sea. Write num_islands(grid) that returns how many separate islands the chart shows.

Examples

Input:  grid = [["1","0","0","1","1"],
                ["1","0","0","0","1"],
                ["0","1","1","0","0"],
                ["0","0","1","0","1"]]
Output: 4

Input:  grid = [["1","0","1"],
                ["0","1","0"],
                ["1","0","1"]]
Output: 5
Explanation: diagonal cells do not touch

Constraints

  • Target: O(m * n) time

Goals

  • Treat a 2D grid as an implicit graph where neighbours are the 4 adjacent cells
  • Flood-fill a region with BFS/DFS and mark cells so they are not counted twice
  • Check grid bounds before touching a neighbour
Starting Python…