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 isConnectedisConnected[i][j] = 1isConnected[i][j]isConnected[j][i]
Example 1
Output: 2
Explanation: {0, 1} and {2}.
Example 2
Output: 3
Explanation: {0}, {1} and {2}.
Example 3
Output: 2
Explanation: {0, 1, 2} and {3, 4}.
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[1, 1, 0]
Example 3 shows why one row is not enough. Row 0 has a road to city 1 only, and isConnected[0][2]
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.
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 intparentparent[i]parent[i] = i
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
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]isConnected[j][i]
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 findfind
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
- First, set
to the number of cities,n . Create the arrayisConnected.length withparent for every city, and setparent[i] = i toprovinces .n - Read the cells above the diagonal with two loops, one inside the other. The outer loop moves
over every city, and for eachi , the inner loop movesi over the cities after it.j - When
is 1, find the leader of cityisConnected[i][j] intoi and the leader of citya intoj . The helperb walks upfind until it reaches a city that points to itself, and halves the path on the way.parent - If
anda differ, point leaderb ata withb , which joins the two groups, and lowerparent[a] = b by one.provinces - When both loops are done, return
.provinces
The main
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:
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[1, 2, 2, 4, 4]provinces
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 finda != b
Complexity
The work is reading the cells above the diagonal, plus two calls to find
- Time: O(n²), because the two loops read n(n - 1) / 2 cells of the matrix, and the
calls add no more than that in total, because path halving keeps their walks short on average.find - Space: O(n), because
holds one entry per city, and the matrix is only read, never copied.parent
Union-find is built up step by step in