vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) { if (positions.size() == 0) { return vector<int>(); } vector<int> res; vector<int> nodes(m * n, -1); vector<pair<int, int>> dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; int count = 0; for (int i = 0; i < positions.size(); ++i) { pair<int, int> pos = positions[i]; int rootIndex = pos.first * n + pos.second; nodes[rootIndex] = rootIndex; count++; for (pair<int, int> d : dir) { int x = pos.first + d.first; int y = pos.second + d.second; int nextIndex = x * n + y; if (x < 0 || x >= m || y < 0 || y >= n || nodes[nextIndex] == -1) { continue; } int nextRootIndex = findIsland(nodes, nextIndex); if (nextRootIndex != rootIndex) { nodes[rootIndex] = nextRootIndex; rootIndex = nextRootIndex; count--; } } res.push_back(count); } return res; }
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) { vector<int> ret; if(m<=0 || n <=0) return ret; int numIsland = 0; //count the number of islands vector<int> roots(m*n, -1); //one island = one tree vector<vector<int>> dirs = {{-1,0},{1,0},{0,1},{0,-1}}; //four directions for(pair<int,int> p:positions){ int root = n * p.first + p.second; roots[root] = root; //add a new island numIsland++; for(vector<int> d:dirs){ int x = p.first + d[0]; int y = p.second + d[1]; int newId = n * x + y; if(x<0 || x>=m || y<0 || y>=n || roots[newId]==-1){ continue; } //not -1, there is already an island int rootId = findIsland(roots, newId); if(root != rootId){ roots[root] = rootId; root = rootId; //union this to neighbor island numIsland--; } } ret.push_back(numIsland); } return ret; }