题目链接:https://leetcode.cn/problems/number-of-islands/submissions/591894989/
题意:
给你一个01 grid,只有上下左右都有1才能链接成一座岛屿(斜着不算),让你求能连成多少个岛屿
思路:
并查集:
把grid每个坐标转化为数字(pos=x*col+y),存储在一维数组father中便于并查集的实现
先把ans设置成为所有1的个数,再把满足条件的1(遍历一遍grid,每当遇到1时看它上边和左边是不是1(注意数组别越界)如果是就merge掉) merge,让ans-merge次数,此时ans就是岛屿总数
class Solution {
public:int ans=0;int father[10000000];void build(){for(int i=0;i<10000000;i++)father[i]=i;}int find(int x){if(x!=father[x]){father[x]=find(father[x]);}return father[x];}void merge(int x,int y){if(find(x)!=find(y)){father[find(x)]=find(y);ans--;}}int pos(int x,int y,int m){return x*m+y;}int numIslands(vector<vector<char>>& grid) {build();int n=grid.size();int m=grid[0].size();for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(grid[i][j]=='1'){ans++;}}} for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(grid[i][j]=='1'){if(i>0&&grid[i-1][j]=='1')merge(pos(i,j,m),pos(i-1,j,m));if(j>0&&grid[i][j-1]=='1')merge(pos(i,j,m),pos(i,j-1,m));}}}return ans;}};