## 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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

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

b'
\n\n

#### Approach #1 DFS [Accepted]

\n

Intuition

\n

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

\n

Algorithm

\n

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

\n

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

\n\n

Complexity Analysis

\n
\n
• \n

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

\n
• \n
• \n

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

\n
• \n
\n
\n

#### Approach #2: BFS [Accepted]

\n

Algorithm

\n

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

\n\n

Complexity Analysis

\n
\n
• \n

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

\n
• \n
• \n

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

\n
• \n
\n
\n

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

\n

Algorithm

\n

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

\n

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

\n

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

\n\n

Complexity Analysis

\n
\n
• \n

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

\n
• \n
• \n

Space complexity : as required by UnionFind data structure.

\n
• \n
\n
\n

Analysis written by: @imsure.

\n

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

\n
\n

Footnotes

\n
\n
\n\n
\n
'