20210107 省份数量

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

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

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

返回矩阵中 省份 的数量。

 

示例 1:


输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
输出:2
示例 2:


输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
输出:3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-provinces
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 public int findCircleNum(int[][] isConnected) {

    }

思路1:

定义 int c=isConnected.length;

当一个省份和另一个省份相连 就可以把这两个省份当成一个省份 同时c-- 把后一个省份定义的1改为0

直到所有数组中没有省份相连时(即数组中1的值只有1个时)抛出c

思路错误 因为关联到时值置0的省份可能会被后面的数组再次关联到

public int findCircleNum(int[][] isConnected) {
         int cd = isConnected.length;
        for (int j=0;j<cd;j++){
            int num=0;
            for (int i=0;i<cd;i++){
                if(isConnected[j][i]==1){
                    num++;
                }
                if(num>1){
                    cd--;//关联时减一个省份
                    for (int k=0;k<cd;k++){
                        isConnected[k][i]=0;
                    }
                }
            }
        }
        return cd;
    }

思路2:

将数组按顺序相加 值为1的是没被关联的 大于1的是被关联的 数组长度减取值为1的个数即是输出

思路错误

    public static int findCircleNum2(int[][] isConnected) {
        int cd = isConnected.length;
        int res=cd;
        int res1=1;
        Set s=new HashSet();
        for (int i=0;i<cd;i++){
            int num=0;
            for (int j=0;j<cd;j++){
                num=isConnected[j][i]+num;
            }
            s.add(num);
            if (num==1){
                res1++;
            }
        }
        if (s.size()==1&&s.contains(1)){
            res1--;
        }
        return res1;
    }

思路3

定义个list<set> set存放各个省份关联的值,如[1,1,0] set中就放1,2 

list就是每个省份关联的集合

若[1,1,0][0,1,1] 那么都放到同一个set中 即set存1,2,3

list的个数就是res

官方

 public int findCircleNum(int[][] isConnected) {
      int provinces = isConnected.length;
        boolean[] visited = new boolean[provinces];
        int circles = 0;
        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < provinces; i++) {
            if (!visited[i]) {
                queue.offer(i);
                while (!queue.isEmpty()) {
                    int j = queue.poll();
                    visited[j] = true;
                    for (int k = 0; k < provinces; k++) {
                        if (isConnected[j][k] == 1 && !visited[k]) {
                            queue.offer(k);
                        }
                    }
                }
                circles++;
            }
        }
        return circles;
    }
原文地址:https://www.cnblogs.com/hbhb/p/14245692.html