Number of Islands - LeetCode Articles
Number of Islands - LeetCode Articles
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
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
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.
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
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 ).
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
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.
Footnotes
1. https://en.wikipedia.org/wiki/Disjoint-set_data_structure (https://en.wikipedia.org/wiki/Disjoint-
set_data_structure) ↩
Comments: 31 Sort By
Preview Post
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
SHOW 12 REPLIES
SHOW 3 REPLIES
2 Share Reply
SHOW 3 REPLIES
SHOW 1 REPLY
SHOW 1 REPLY
"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
https://leetcode.com/articles/number-of-islands/ 6/6