# Union Find by adding labels and changing labels(naive but not slow)

• ``````class Solution {
private:
vector<vector<int>> Labels;
unordered_map<int, vector<pair<int,int>>> Islands;
int num_islands;
int max_label;

public:

vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
Labels= vector<vector<int>> (m, vector<int> (n,0));
num_islands=0;
max_label=0;
vector<int> result;
for (auto P: positions){
result.push_back(num_islands);
}
return result;
}

void AddLand (int x, int y, int m, int n) {
int A[5]={0,1,0,-1,0};
for (int i=0; i<4; i++){
if (x+A[i]>=0 && x+A[i]<m && y+A[i+1]>=0 && y+A[i+1]<n) {
}
}
max_label++;
Labels[x][y]=max_label;
Islands[max_label].push_back(make_pair(x,y));
}
else {
Labels[x][y]=K;
Islands[K].push_back(make_pair(x,y));
if (k!=K) {
for (auto p: Islands[k]){
Labels[p.first][p.second]=K;
Islands[K].push_back(p);
}
Islands[k].clear();
}
}
}
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.