Number of Islands⚓︎
Description⚓︎
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return 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:
- Output:
1
Example 2:
- Input:
- Output:
3
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
is'0'
or'1'
.
Solution⚓︎
DFS⚓︎
See reference (Chinese).
- Time complexity: \(O(nm)\);
- Space complexity: \(O(nm)\).
BFS⚓︎
Union Find⚓︎
Breakdown:
- Data Structures:
vector<int> p;
: Parent array for Union-Find, wherep[i]
represents the parent of elementi
.int columns;
: Stores the number of columns in the grid to convert 2D indices into 1D.int sets;
: Tracks the number of disjoint sets (islands).- Build Function:
- Initializes the parent array
p
for each cell in the grid that is land ('1'). Each land cell is initially its own parent, indicating a separate island. - The
sets
variable is incremented for each land cell, assuming each cell is an isolated island initially. - Find Function:
- Implements path compression for efficient finds. If an element's parent is not itself, it recursively finds the ultimate parent and updates the parent to point directly to the ultimate parent, reducing future find times.
- UnionSets Function:
- Merges two sets (islands) into one by connecting their roots. If the roots are different, it sets one root to be the parent of the other, effectively merging the two sets. It decrements the
sets
counter since two islands merge into one. - Index Function:
- Converts 2D grid coordinates to a 1D index. This is necessary because the Union-Find structure is represented as a 1D array.
- numIslands Function:
- Iterates over the grid, and for each land cell, it tries to union it with its adjacent (up and left, to avoid redundancy) land cells. This step effectively groups adjacent lands into single islands.
Time Complexity:
- Build Function: \(O(MN)\) where \(M\) is the number of rows and \(N\) is the number of columns, as it iterates over all cells.
- Union and Find Operations: Amortized \(O(\alpha(MN))\) for each operation, where \(\alpha\) is the Inverse Ackermann function, which grows extremely slowly and is practically constant for all conceivable problem sizes.
- Total Time Complexity: \(O(MN \times \alpha(MN))\), considering both the initial building phase and the union-find operations for each cell. The actual impact of \(\alpha(MN)\) is so minimal that the time complexity can be considered nearly linear to the input size.
Space Complexity:
- Parent Array \(p\): \(O(MN)\) for storing the parent of each cell.
- Total Space Complexity: \(O(MN)\), as the primary storage is the parent array, with no additional significant storage.