← All problems

547. Number of Provinces

MediumOpen on LeetCodeProblem statement

Problem Statement

547. Number of Provinces

Medium


There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

 

Example 1:

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2

Example 2:

Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3

 

Constraints:

Java

Source file
class Solution {
        private class UnionFind {
        public int[] root;
        public int[] rank;

        public UnionFind(int size) {
            root = new int[size];
            rank = new int[size];
            for (int i = 0; i < size; i++) {
                root[i] = i;
                rank[i] = 1;
            }
        }

        public int find(int node) {
            if (root[node] != node)
                return root[node] = find(root[node]);
            return node;
        }

        public void union(int u, int v) {
            int rootU = find(u);
            int rootV = find(v);
            if (rootU == rootV)
            return;
            if (rank[rootU] > rank[rootV])
                root[rootV] = rootU;
            else if (rank[rootU] < rank[rootV])
                root[rootU] = rootV;
            else {
                root[rootV] = rootU;
                rank[rootU] += 1;
            }
        }

        public boolean connected(int u, int v) {
            return find(u) == find(v);
        }
    }
    
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        UnionFind uf = new UnionFind(n);
        for(int i=0; i<n; i++)
            for(int j=0; j<n; j++)
                if(isConnected[i][j]==1)
                    uf.union(i, j);
        Set<Integer> roots = new HashSet<>();
        for(int i=0; i<n; i++)
            roots.add(uf.find(i));
        return roots.size();
    }
}