LeetCode 547. Number of Provinces

Number of provinces


topic

Insert picture description hereInsert picture description here


Ideas

The problem is to find the number of connected components of the undirected graph, and the independent vertex is also regarded as a connected component.


Implementation code (Java)

class Solution {
    
    

    int[] f;
    public int findCircleNum(int[][] isConnected) {
    
    
        int n = isConnected[0].length;
        f = new int[n+1];
        init(f,n);
        for(int i = 0;i<n;i++){
    
    
            for(int j = 0;j<n;j++) {
    
    
                if(i!=j && isConnected[i][j] == 1) {
    
    
                    merge(i+1,j+1);
                }
            }
        }
        int cnt = 0;
        for(int i = 1;i<=n;i++){
    
    
            if(i == f[i]) {
    
    
                cnt++;
            }
        }
        return cnt;
    }

    public void init(int[] f,int n) {
    
    
        for(int i = 1;i<=n;i++) {
    
    
            f[i] = i;
        }
    }

    public int findFx(int x) {
    
    
        if( x == f[x]) {
    
    
            return x;
        }
        x = findFx(f[x]);
        return x;
    }

    public void merge(int x,int y) {
    
    
        x = findFx(x);
        y = findFx(y);
        if(x != y) {
    
    
            f[y] = x;
        }
    }

}

Insist on sharing, insist on originality, pretty girls who like bloggers can check out the blogger's homepage blog!
Your likes and favorites are my greatest appreciation for sharing blogs!
Blogger blog address: https://blog.csdn.net/weixin_43967679

Guess you like

Origin blog.csdn.net/weixin_43967679/article/details/112304495