具体思想:
个人感觉会搜索爆时间,所以采用unordered_map保留了根节点信息;
刷题不仔细,各种bug;
思路跟简单;
具体代码:
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
father.resize(m*n,-1);
int ret=0;
vector<int>res;
for(auto& vec:positions){
int x=vec[0];
int y=vec[1];
int index=x*n+y;
if(findfather(index)!=-1){
res.push_back(ret);
continue;
}
//如果为空,进行四个方向的判断;
vector<int>charge;
set<int>se;//看看四个方向有几个势力;
for(int i=0;i<4;i++){
int nx=x+dir[i][0];
int ny=y+dir[i][1];
if(nx<0||nx>=m||ny<0||ny>=n||findfather(nx*n+ny)==-1){
continue;
}
se.insert(findfather(nx*n+ny));
}
if(se.size()==0){
//如果周围没有岛屿;
ump[index].push_back(index);//自己做根节点;
father[index]=index;
ret++;
}else if(se.size()==1){
//如果周围势力相同;
ump[*se.begin()].push_back(index);
father[index]=*se.begin();
}else{
//如果周围多种势力,以第一股势力作为根节点;
ret-=se.size()-1;
int root=*se.begin();
se.erase(se.begin());
for(auto it=se.begin();it!=se.end();it++){
int temp=*it;
for(auto in:ump[temp]){
father[in]=root;
}
ump[root].insert(ump[root].end(),ump[temp].begin(),ump[temp].end());
ump[temp].resize(0);
}
father[index]=root;
ump[root].push_back(index);
}
res.push_back(ret);
}
return res;
}
int findfather(int index){
return father[index];
}
private:
vector<vector<int>> dir={{0,1},{1,0},{-1,0},{0,-1}};
vector<int>father;
unordered_map<int,vector<int>>ump;
};