0% found this document useful (0 votes)
80 views6 pages

Number of Islands - LeetCode Articles

Uploaded by

jon monroe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views6 pages

Number of Islands - LeetCode Articles

Uploaded by

jon monroe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

10/5/2019 Number of Islands - LeetCode Articles

 Articles  200. Number of Islands 

 Previous (/articles/search-a-2d-matrix-ii/) Next  (/articles/split-array-largest-sum/)

200. Number of Islands  (/problems/number-of-islands/)


Dec. 15, 2017 | 112.9K views

Average Rating: 4.69 (29 votes)

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

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.

https://leetcode.com/articles/number-of-islands/ 1/6
10/5/2019 Number of Islands - LeetCode Articles

   1/8

C++ Java  Copy

1 class Solution {
2 private:
3 void dfs(vector<vector<char>>& grid, int r, int c) {
4 int nr = grid.size();
5 int nc = grid[0].size();
6
7 grid[r][c] = '0';
8 if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(grid, r - 1, c);
9 if (r + 1 < nr && grid[r+1][c] == '1') dfs(grid, r + 1, c);
10 if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c - 1);
11 if (c + 1 < nc && grid[r][c+1] == '1') dfs(grid, r, c + 1);
12 }
13
14 public:
15 int numIslands(vector<vector<char>>& grid) {
16 int nr = grid.size();
17 if (!nr) return 0;
18 int nc = grid[0].size();
19
20 int num_islands = 0;
21 for (int r = 0; r < nr; ++r) {
22 for (int c = 0; c < nc; ++c) {
23 if (grid[r][c] == '1') {
24 ++num_islands;
25 dfs(grid, r, c);
26 }
27 }

Complexity Analysis

Time complexity : O(M × N ) where M is the number of rows and N is the number of columns.
Space complexity : worst case O(M × N ) in case that the grid map is filled with lands where DFS
goes by M × N 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.

https://leetcode.com/articles/number-of-islands/ 2/6
10/5/2019 Number of Islands - LeetCode Articles

C++ Java  Copy

1 class Solution {
2 public:
3 int numIslands(vector<vector<char>>& grid) {
4 int nr = grid.size();
5 if (!nr) return 0;
6 int nc = grid[0].size();
7
8 int num_islands = 0;
9 for (int r = 0; r < nr; ++r) {
10 for (int c = 0; c < nc; ++c) {
11 if (grid[r][c] == '1') {
12 ++num_islands;
13 grid[r][c] = '0'; // mark as visited
14 queue<pair<int, int>> neighbors;
15 neighbors.push({r, c});
16 while (!neighbors.empty()) {
17 auto rc = neighbors.front();
18 neighbors.pop();
19 int row = rc.first, col = rc.second;
20 if (row - 1 >= 0 && grid[row-1][col] == '1') {
21 neighbors.push({row-1, col}); grid[row-1][col] = '0';
22 }
23 if (row + 1 < nr && grid[row+1][col] == '1') {
24 neighbors.push({row+1, col}); grid[row+1][col] = '0';
25 }
26 if (col - 1 >= 0 && grid[row][col-1] == '1') {
27 neighbors.push({row, col-1}); grid[row][col-1] = '0';

Complexity Analysis

Time complexity : O(M × N ) where M is the number of rows and N is the number of columns.
Space complexity : O(min(M , N )) because in worst case where the grid is filled with lands, the size
of queue can grow up to min(M , N ).

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 (https://leetcode.com/articles/redundant-
connection/).

https://leetcode.com/articles/number-of-islands/ 3/6
10/5/2019 Number of Islands - LeetCode Articles

   1/6

C++ Java  Copy

1 class UnionFind {
2 public:
3 UnionFind(vector<vector<char>>& grid) {
4 count = 0;
5 int m = grid.size();
6 int n = grid[0].size();
7 for (int i = 0; i < m; ++i) {
8 for (int j = 0; j < n; ++j) {
9 if (grid[i][j] == '1') {
10 parent.push_back(i * n + j);
11 ++count;
12 }
13 else parent.push_back(-1);
14 rank.push_back(0);
15 }
16 }
17 }
18
19 int find(int i) { // path compression
20 if (parent[i] != i) parent[i] = find(parent[i]);
21 return parent[i];
22 }
23
24 void Union(int x, int y) { // union with rank
25 int rootx = find(x);
26 int rooty = find(y);
27 if (rootx != rooty) {

Complexity Analysis

Time complexity : O(M × N ) where M is the number of rows and N 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 : O(M × N ) as required by UnionFind data structure.

Analysis written by: @imsure (https://leetcode.com/imsure).

Thanks to @williamfu4leetcode (https://leetcode.com/williamfu4leetcode/) for correcting the space


complexity analysis of BFS approach.

Footnotes

1. https://en.wikipedia.org/wiki/Disjoint-set_data_structure (https://en.wikipedia.org/wiki/Disjoint-
set_data_structure) ↩

Rate this article:

 Previous (/articles/search-a-2d-matrix-ii/) Next  (/articles/split-array-largest-sum/)

Comments: 31 Sort By 

Type comment here... (Markdown is supported)

 Preview Post

asheth111 (asheth111)  167  October 8, 2018 9:28 PM 


Python solution beats 80%

Read More

https://leetcode.com/articles/number-of-islands/ 4/6
10/5/2019 Number of Islands - LeetCode Articles
27    Share  Reply

SHOW 3 REPLIES

harryzou (harryzou)  20  December 22, 2018 4:16 PM 


Can someone explain the validity of BFS space complexity? Thank you.
7    Share  Reply

SHOW 12 REPLIES

djyale (djyale)  13  August 17, 2018 9:45 PM 


I'm getting Time Limit Exceeded after implementing BFS in Python with 38/47 test cases passed. Does anyone have a
passing BFS solution in Python?
4    Share  Reply

SHOW 3 REPLIES

embahsi (embahsi)  3  August 28, 2019 12:25 PM 


Explanation of BFS Space Complexity: Min(M, N).
Think about an example where dif(M, N) is big like 3x1000 grid. And the worst case is when we start from the middle of
the grid.
Imagine how the processed points form a shape in the grid. It will be like a diamond and at some point, it will reach the
longer edge of the grid. The possible shape at time t would be:
Read More

2    Share  Reply

angelapan (angelapan)  10  April 18, 2019 9:17 PM 


the BFS soluion, fill a 4 row, 3 col with all 1s. run it with the code provided. there can be max 4 elements lined up in the
queue. so it's probably Max(M, N). definitely not Min(M,N)
2    Share  Reply

ldong87 (ldong87)  3  February 12, 2019 12:05 AM 


The space complexity is not correct for BFS. It's also not max(M, N). Simple 5X4 matrix with all '1's can show this.
However, it's not clear what is the actual space complexity.
2    Share  Reply

SHOW 3 REPLIES

imsure (imsure)  29  February 13, 2018 11:32 AM 


@ jocelynayoga Thanks for the comments! Think about the worse case: the grid if filled with '1'. During the first iteration,
it takes MN to do BFS to identify the giant island. After that, it takes another MN to scan the grid, even though all the cells
become '0' by then. So the total is 2MN which is still O(M*N).
2    Share  Reply

praveen14612 (praveen14612)  1  May 13, 2019 9:51 PM 


For #2: BFS, looks like the q grows < m+n range, so space complexity is close to O(M+N) rather than O(min(M,N)) ????
1    Share  Reply

SHOW 1 REPLY

roshetty18 (roshetty18)  38  August 25, 2018 7:50 AM 


wont the time complexity be O(sqr(mxn)) cause once its out of dfs function it will still traverse the entire grid again which
is full of zeros. Like suppose the entire grid is an big island.You enter dfs and travers entire array till all elements are zero
and come out.but the for loop will still traverse from grid[0][1] till end
1    Share  Reply

SHOW 1 REPLY

sai_manoj_kumar (sai_manoj_kumar)  6  March 17, 2019 2:23 PM 


In DFS space complexity, how can we conclude this:

"Space complexity : O(min(M,N)) because in worst case where the grid is filled with lands, the size of queue can grow
up to min(M,N)."
1    Share  Reply

SHOW 2 REPLIES

https://leetcode.com/articles/number-of-islands/ 5/6
10/5/2019 Number of Islands - LeetCode Articles

 1 2 3 4 

Copyright © 2019 LeetCode


Help Center (/support/) | Students (/students) | Terms (/terms/) | Privacy Policy (/privacy/)
United States (/region/)

https://leetcode.com/articles/number-of-islands/ 6/6

You might also like