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.
Intuition
\nTreat the 2d grid map as an undirected graph and there is an edge\nbetween two horizontally or vertically adjacent nodes of value \'1\'.
\nAlgorithm
\nLinear 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.
\nThe algorithm can be better illustrated by the animation below:\n!?!../Documents/200_number_of_islands_dfs.json:1024,768!?!
\n\nComplexity Analysis
\nTime complexity : where is the number of rows and\n is the number of columns.
\nSpace complexity : worst case in case that the grid map\n is filled with lands where DFS goes by deep.
\nAlgorithm
\nLinear 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\nComplexity Analysis
\nTime complexity : where is the number of rows and\n is the number of columns.
\nSpace complexity : because in worst case where the\n grid is filled with lands, the size of queue can grow up to min().
\nAlgorithm
\nTraverse 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.
\nFor details regarding to Union Find, you can refer to this article.
\nThe algorithm can be better illustrated by the animation below:\n!?!../Documents/200_number_of_islands_unionfind.json:1024,768!?!
\n\nComplexity Analysis
\nTime 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.
\nSpace complexity : as required by UnionFind data structure.
\nAnalysis written by: @imsure.
\nThanks to @williamfu4leetcode for correcting the space complexity analysis of BFS approach.
\nFootnotes
\n