Number of Islands II Posted on 2018-10-12 Descriptionhttps://leetcode.com/problems/number-of-islands-ii/description/ Solution1234567891011121314151617181920212223242526272829303132333435363738394041424344454647class Solution {public: vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) { vector<int> ret; vector<int> roots(m * n, -1); vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int count = 0; for (auto& position : positions) { int x = position.first; int y = position.second; int pos = x * n + y; if (roots[pos] == -1) { roots[pos] = pos; count += 1; } for (auto& dir : dirs) { int newX = x + dir[0]; int newY = y + dir[1]; int newPos = newX * n + newY; if (newX < 0 || newX >= m || newY < 0 || newY >= n || roots[newPos] == -1) continue; int rootCur = findRoot(roots, pos); int rootNew = findRoot(roots, newPos); if (rootCur != rootNew) { roots[rootCur] = rootNew; --count; } } ret.push_back(count); } return ret; } int findRoot(vector<int>& roots, int pos) { stack<int> st; while (roots[pos] != pos) { pos = roots[pos]; st.push(pos); } while(!st.empty()) { roots[st.top()] = pos; st.pop(); } return pos; }};