You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0’s represent water and 1’s represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0’s).
We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.
Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.
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.
intfind(int n){ return group[n] == n ? n : group[n] = find(group[n]); }
unordered_set<int> near(int y, int x, int n, int m){ unordered_set<int> res; for(int i = 0; i < 4; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and0 <= nx and nx < m and grid[ny].count(nx)) { res.insert( find(grid[ny][nx])); } } return res; }
voiduni(unordered_set<int> islands){ int mi = *min_element(islands.begin(),islands.end()); for(auto island : islands) { group[island] = mi; } } public: vector<int> numIslands2(int n, int m, vector<vector<int>>& positions){ vector<int> res; int island = 0; int cnt = 0; for(auto po : positions) { int y = po[0], x = po[1]; if(grid[y].count(x)) { res.push_back(cnt); continue; } auto neighbor = near(y,x,n,m); if(neighbor.empty()) { grid[y][x] = ++island; group[island] = island; cnt++; } elseif(neighbor.size() == 1) { grid[y][x] = *neighbor.begin(); } else { grid[y][x] = *min_element(neighbor.begin(), neighbor.end()); cnt -= (neighbor.size() - 1); uni(neighbor); } res.push_back(cnt); } return res; } };