Number of Provinces

Count the groups of cities that are linked by roads, directly or through other cities.

There are n cities, numbered 0 to n - 1, and an n x n matrix isConnected. isConnected[i][j] = 1 means city i and city j are directly connected, and 0 means they are not. The matrix is symmetric, so isConnected[i][j] equals isConnected[j][i], and every city counts as connected to itself, so the diagonal is all 1s. A province is a group of cities that are connected directly or through other cities, with no connection to any city outside the group. Return the number of provinces.

Example 1
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Explanation: {0, 1} and {2}.
Example 2
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Explanation: {0}, {1} and {2}.
Example 3
Input: isConnected = [[1,1,0,0,0],[1,1,1,0,0],[0,1,1,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 2
Explanation: {0, 1, 2} and {3, 4}.
Solution

The Idea

Picture a region of small cities with a few roads between them. If you can drive from one city to another, on one road or through other cities, the two belong to the same province. The question is how many separate provinces the roads make.

The roads come as a table. Row i and column j of isConnected hold a 1 when a road joins city i and city j. In Example 1, row 0 is [1, 1, 0]: the first 1 is city 0 itself, and the second 1 is a road from city 0 to city 1. City 2 has a 1 only in its own column, so it has no road at all. That gives two provinces, {0, 1} and {2}. A table like this, with one row and one column per city and a 1 for every road, is called an adjacency matrix.

Example 3 shows why one row is not enough. Row 0 has a road to city 1 only, and isConnected[0][2] is 0. Yet city 0 and city 2 are in the same province, because row 1 has roads to both of them. So how do we tell that two cities belong together without retracing the roads every time?

Give each group one city as its leader. Every city keeps a pointer to a city of its group, and following the pointers always ends at the leader, which points to itself. Two cities are in the same province exactly when their pointers lead to the same leader. Look at the picture below.

Left: cities 0 to 4 of Example 3 with roads 0-1, 1-2 and 3-4, forming province 1 and province 2. Right: the parent pointers after the merges. 0 points to 1, 1 points to 2, and 3 points to 4. Cities 2 and 4 point to themselves and are marked leader.

On the left are the five cities of Example 3 and their three roads. On the right, labelled "parent: who each city points to", 0 points to 1 and 1 points to 2. City 2, marked leader, points to itself. So city 0 reaches leader 2 in two steps, and city 1 in one. Cities 3 and 4 have a separate leader, 4.

The pointers are built one road at a time. At the start each city is its own leader, so there are five groups. The road 0-1 joins two groups into one, and so does the road 1-2. The road 3-4 joins a third pair. Three joins took five groups down to two, the answer. A road between two cities that already share a leader joins nothing.

This way of keeping groups is called union-find: "find" follows the pointers from a city to its leader, and "union" joins two groups by pointing one leader at the other. In graph terms, the cities are vertices, the roads are edges, and a province is a connected component.

Solution Approach

Turning the leaders into code means settling four things: where the pointers are kept, which cells of the matrix to read, when the count of provinces drops, and how to keep the walk to a leader short. A search outward from each city works too, and comes last as an alternative.

Where the pointers are kept

What does each city need to remember? Only the city it points to. Cities are numbered 0 to n - 1, so an int array named parent holds them all: parent[i] is the city that city i points to. At the start parent[i] = i, so every city leads a group of one, and the count of provinces is n.

Without leaders, deciding whether cities 0 and 2 belong together means walking the roads from city 0 until city 2 turns up or the roads run out. Doing that for every road repeats the same walks again and again. With parent, the question becomes a short walk up the pointers from each city.

Which cells to read

Does every cell of the matrix tell us something new? No. The diagonal only says that a city is connected to itself. And since isConnected[i][j] equals isConnected[j][i], every road appears twice. Reading the cells above the diagonal, where j is greater than i, sees each road once. For Example 3 that is 10 of the 25 cells.

When the count drops

Should every 1 lower the count? Only when the two cities have different leaders. Take three cities that all have roads to each other. The roads 0-1 and 0-2 join all three into one group. The third road, 1-2, then finds both cities already under the same leader, so it must not lower the count again.

Keeping the walk to a leader short

How long can the walk up the pointers get? A long chain of roads can build a long chain of pointers, as 0, 1 and 2 already do in the picture. So find shortens the chain while it walks: each city it passes is pointed at the city two steps up. In the picture, find on city 0 would set city 0 to point straight at 2. Later walks from city 0 then take one step. Skipping one level on every step like this is called path halving.

Alternative: exploring from each city

Union-find is not required here: a depth-first search (DFS) also works. Start at a city not seen yet and follow its roads to new cities, going as deep as possible before turning back, until the whole province is seen. Each fresh start is one more province. It reads the same matrix rows and is just as fast here.

Java Solution

The method findCircleNum works in these steps:

  1. First, set n to the number of cities, isConnected.length. Create the array parent with parent[i] = i for every city, and set provinces to n.
  2. Read the cells above the diagonal with two loops, one inside the other. The outer loop moves i over every city, and for each i, the inner loop moves j over the cities after it.
  3. When isConnected[i][j] is 1, find the leader of city i into a and the leader of city j into b. The helper find walks up parent until it reaches a city that points to itself, and halves the path on the way.
  4. If a and b differ, point leader a at b with parent[a] = b, which joins the two groups, and lower provinces by one.
  5. When both loops are done, return provinces.

The main method runs the three examples, a single city, and three cities that all have roads to each other.

Java
public class NumberOfProvinces {

    public static int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        int[] parent = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;                    // every city starts as its own leader
        }
        int provinces = n;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) { // upper half only: the matrix is symmetric
                if (isConnected[i][j] == 1) {
                    int a = find(parent, i);
                    int b = find(parent, j);
                    if (a != b) {             // two different provinces meet
                        parent[a] = b;
                        provinces--;
                    }
                }
            }
        }
        return provinces;
    }

    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];    // path halving: skip one step up
            x = parent[x];
        }
        return x;
    }

    public static void main(String[] args) {
        System.out.println(findCircleNum(new int[][] {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}));
        System.out.println(findCircleNum(new int[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}));
        System.out.println(findCircleNum(new int[][] {
            {1, 1, 0, 0, 0},
            {1, 1, 1, 0, 0},
            {0, 1, 1, 0, 0},
            {0, 0, 0, 1, 1},
            {0, 0, 0, 1, 1}}));
        System.out.println(findCircleNum(new int[][] {{1}}));
        System.out.println(findCircleNum(new int[][] {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}));
    }
}

Running it prints:

Output
2
3
2
1
1

The opening 2 and 3 match Examples 1 and 2. The 2 on the third line is Example 3, and its run ends with parent as [1, 2, 2, 4, 4]: the pointers in the picture, with leaders 2 and 4. The single city gives 1, because the inner loop finds no cell above the diagonal and provinces keeps its starting value.

Look at the last line. The three cities have three roads, but the count dropped only twice, from 3 to 1. The road 0-1 pointed city 0 at 1, and the road 0-2 pointed leader 1 at 2. On the road 1-2, both find calls returned 2, so nothing changed. A version that lowers the count for every 1 above the diagonal, with no a != b check, returns 0 for this matrix.

Complexity

The work is reading the cells above the diagonal, plus two calls to find for every road.

  • Time: O(n²), because the two loops read n(n - 1) / 2 cells of the matrix, and the find calls add no more than that in total, because path halving keeps their walks short on average.
  • Space: O(n), because parent holds one entry per city, and the matrix is only read, never copied.

Union-find is built up step by step in Number of Connected Components.