Number of Islands

Question (LC.200)

Given a 2D grid consists of "1"s and "0"s, count the number of connected "1"s.

An island ("1"s) can be connected vertically and horizontally. Assume all 4 edges are surrounded by water.

Example

The given input is a char[][].

11110
11010
11000
00000

Output: 1

11000
11000
00100
00011

Output: 1+1+1 = 3

Analysis

This question is essentially searching connected components in a simple graph. We can solve it with either BFS or DFS. We prefer BFS over DFS because 1 1 1 1 1 ... 1 can overflow the call stack. Say we want to eat a hamburger. Do you want to eat normally by taking a couple bites around the side? Or do you want to keep biting in one direction until you reach the end of that direction? Sure both methods can finish the burger, but your mouth might get very full by choosing the second way.

BFS Approach

BFS Code

Time Complexity

O(mn)

DFS Approach

Follow Up #0

Only destroy the island if the number of 1s is less than k

  • have a flag at the end of the path, if path_length < k, give permission to destroy the island on the back back (backtracking) otherwise label it as red zone (label is -1 or something so we don't touch it). So we want to measure how long this subway is before we eat it backward. i.e. if it's 12in we don't want to eat it, label it red. But if it's 6in, then eat it backward.

Follow Up #1

Count number of lakes

Follow up #2

Measure the length of the seashore

Number of Islands II (Union Find)

Reference

Segmentfault Number of Islands by Ethan Li

Last updated