Java——省份数量

题目描述

有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。

省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。

给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。

例如:
在这里插入图片描述

思路

这道题可以使用上一篇博客讲到的并查集来解决

两个城市相连或间接相连,说明这两个城市在一个集合中,那么我们遍历这个二维数组,将所有为1的值对应的下标都让他们在并查集中相连,最后获取并查集中集合的数目即可

这里需要注意的是,我们的并查集的大小可以用二维数组中一行的长度,因为所有的城市就在这个矩阵的横轴或纵轴上排列表示

并查集的相关概念和实现代码可以到我的上一篇博客中看

代码

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        MyUnionFindSet ufs = new MyUnionFindSet(n);
        for(int i = 0; i < isConnected.length; i++){
            for(int j = 0; j < isConnected[i].length; j++){
                if(isConnected[i][j] == 1){
                    ufs.union(i,j);
                }
            }
        }
        return ufs.getCount();
    }
}
class MyUnionFindSet {
    public int[] elem;
    public int usedSize;

    public MyUnionFindSet(int n){
        this.elem = new int[n];
        Arrays.fill(elem, -1);//初始化数组全为-1
    }

    /**
     * 查询x1和x2是否在同一个集合中
     * @param x1
     * @param x2
     * @return
     */
    public boolean isSameUnionFindSet(int x1, int x2){
        int index1 = findRoot(x1);
        int index2 = findRoot(x2);

        if(index1 == index2){
            return true;
        }
        return false;
    }

    /**
     * 查找x下标数据的根节点
     * @param x
     * @return 根节点的下标
     */
    public int findRoot(int x){
        if(x < 0){
            throw new ArrayIndexOutOfBoundsException("下标不能是负数");
        }

        while(elem[x] >= 0){
            x = elem[x];
        }
        return x;
    }

    /**
     * 合并x1,x2所在的两个集合
     * @param x1
     * @param x2
     */
    public void union(int x1, int x2){
       int index1 = findRoot(x1);
       int index2 = findRoot(x2);

       if(index1 == index2){
           System.out.println("x1和x2已经在同一个集合中了");
           return;
       }

       elem[index1] = elem[index1] + elem[index2];
       elem[index2] = index1;
    }

    public int getCount(){
        int count = 0;
        for (int x:elem) {
            if(x < 0){
                count++;
            }
        }
        return count;
    }

    public void print(){
        for (int x:elem) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值