305. Number of Islands II
Description
A 2d grid map ofm
rows andn
columns is initially filled with water. We may perform anaddLandoperation which turns the water at position (row, col) into a land. Given a list of positions to operate,count the number of islands after eachaddLandoperation. 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:
Givenm = 3, n = 3
,positions = [[0,0], [0,1], [1,2], [2,1]]
.
Initially, the 2d gridgrid
is filled with water. (Assume 0 represents water and 1 represents land).
0 0 0
0 0 0
0 0 0
Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
1 0 0
0 0 0 Number of islands = 1
0 0 0
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
1 1 0
0 0 0 Number of islands = 1
0 0 0
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
1 1 0
0 0 1 Number of islands = 2
0 0 0
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
1 1 0
0 0 1 Number of islands = 3
0 1 0
We return the result as an array:[1, 1, 2, 3]
Challenge:
Can you do it in time complexity O(k log mn), where k is the length of thepositions
?
Note
Union-Find
Code
class Solution {
private:
vector<int> uf;
int cnt = 0;
int find(int index) {
if(uf[index] == index) {
return index;
}
return uf[index] = find(uf[index]);
}
void unionFind(int a, int b) {
int x = find(a);
int y = find(b);
if(x != y) {
uf[x] = y;
--cnt;
//cout << "[" << a << ", " << b << "]->[" << uf[a] << ", " << uf[b] << "]" << endl;
}
}
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> rst;
if(m == 0 || n == 0 || positions.size() == 0)
return rst;
uf = vector<int>(m * n + 1, 0);
vector<int> tracker = vector<int>(m * n + 1, 0);
vector<int> dy = {0,0,1,-1};
vector<int> dx = {1,-1,0,0};
for(int loop = 0; loop < uf.size(); ++loop) {
uf[loop] = loop;
}
for(auto position : positions) {
int curIndex = position.first * n + position.second;
//cout << "[" << position.first << ", " << position.second << endl;
tracker[curIndex] = 1;
++cnt;
for(int loop = 0; loop < dy.size(); ++loop) {
if(position.first + dy[loop] >= 0 && position.first + dy[loop] < m && position.second + dx[loop] >= 0 && position.second + dx[loop] < n ) {
int tmp = (position.first + dy[loop]) * n + position.second + dx[loop];
if(tracker[tmp] == 1) {
unionFind(tmp, curIndex);
}
}
}
rst.push_back(cnt);
}
return rst;
}
};