[One question per day] Deduct 547. The number of provinces (and collect exercise 02)

Title description ( portal )

There are n cities, some of which are connected to each other, and some are not connected. If city a and city b are directly connected, and city b is directly connected to city c, then city a and city c are indirectly connected.

A province is a group of directly or indirectly connected cities. The group does not contain other unconnected cities.

Give you an nxn matrix isConnected, where isConnected[i][j] = 1 means that the ith city and the jth city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.

Returns the number of provinces in the matrix.

Example 1:
Insert picture description here

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

Example 2:

Insert picture description here

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

Problem solving ideas & code implementation

This question is similar to: [One question every day] Niu Ke: Calculating Moments (Consolidated Checking Exercise 01)
Knowledge Points: [High-level Data Structure] Consolidating Detailed Explanations

/**
 * @ClassName lk547
 * @Description :TODO
 * @Author Josvin
 * @Date 2021/01/16/12:01
 */
public class lk547 {
    
    
    private static int count;
    private static int[] id;
    private static int[] size;
    public int findCircleNum(int[][] isConnected) {
    
    
        Union_Find(isConnected);
        return count;
    }

    private void Union_Find(int[][] isConnected) {
    
    
        int N = isConnected.length;
        id = new int[N];
        size = new int[N];
        count = N;
        for (int i = 0; i < N; i++) {
    
    
            id[i] = i;
            size[i] = 1;
        }

        for (int i = 0; i < N; i++) {
    
    
            for (int j = 0; j < N; j++) {
    
    
                if (1 == isConnected[i][j]) {
    
    
                    Union(i, j);
                }
            }
        }
    }

    private static void Union(int p, int q) {
    
    
        int proot = Find(p);
        int qroot = Find(q);
        if (proot == qroot) {
    
    
            return;
        }
        if (size[p] > size[q]) {
    
    
            id[proot] = qroot;
            size[qroot] += size[p];

        } else {
    
    
            id[qroot] = proot;
            size[proot] += size[q];
        }
        count--;
    }

    private static int Find(int p) {
    
    
        if (id[p] != p) {
    
    
            id[p] = Find(id[p]);
        }
        return id[p];
    }
}

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/112699866