200. Number of Islands


Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


Approach #1 DFS [Accepted]

Intuition

Treat the 2d grid map as an undirected graph and there is an edge between two horizontally or vertically adjacent nodes of value '1'.

Algorithm

Linear scan the 2d grid map, if a node contains a '1', then it is a root node that triggers a Depth First Search. During DFS, every visited node should be set as '0' to mark as visited node. Count the number of root nodes that trigger DFS, this number would be the number of islands since each DFS starting at some root identifies an island.

The algorithm can be better illustrated by the animation below: !?!../Documents/200_number_of_islands_dfs.json:1024,768!?!

Complexity Analysis

  • Time complexity : where is the number of rows and is the number of columns.

  • Space complexity : worst case in case that the grid map is filled with lands where DFS goes by deep.


Approach #2: BFS [Accepted]

Algorithm

Linear scan the 2d grid map, if a node contains a '1', then it is a root node that triggers a Breadth First Search. Put it into a queue and set its value as '0' to mark as visited node. Iteratively search the neighbors of enqueued nodes until the queue becomes empty.

Complexity Analysis

  • Time complexity : where is the number of rows and is the number of columns.

  • Space complexity : because in worst case where the grid is filled with lands, the size of queue can grow up to min().


Approach #3: Union Find (aka Disjoint Set) [Accepted]

Algorithm

Traverse the 2d grid map and union adjacent lands horizontally or vertically, at the end, return the number of connected components maintained in the UnionFind data structure.

For details regarding to Union Find, you can refer to this article.

The algorithm can be better illustrated by the animation below: !?!../Documents/200_number_of_islands_unionfind.json:1024,768!?!

Complexity Analysis

  • Time complexity : where is the number of rows and is the number of columns. Note that Union operation takes essentially constant time1 when UnionFind is implemented with both path compression and union by rank.

  • Space complexity : as required by UnionFind data structure.


Analysis written by: @imsure.

Thanks to @williamfu4leetcode for correcting the space complexity analysis of BFS approach.


Footnotes