Statementâ–¼
Given cities
, where cities[i][j]
cities[i][j]
Note: If city
A is directly connected to cityB and cityB is directly connected to cityC , then cityA is indirectly connected to cityC .
The task is to return the total number of groups of connected cities directly or indirectly. These groups are referred to as
Constraints:
1≤ n ≤200 n== cities.length
n== cities[i].length
, where0≤ i ≤n cities[i][j]
is either0 or1 .cities[i][i]
==1 cities[i][j]
== cities[j][i]
Solution
This solution uses the union find approach to find the number of provinces formed by the given cities. The union find approach groups cities that are connected directly or indirectly by using the Find
operation to check which group a city belongs to and the Union
operation to merge the roots of connected cities. Each root in the graph would act as a city, and a cluster of connected roots would represent a province, and a city with no connections would also be represented as a province.
Here’s the step-by-step implementation of the solution:
Calculate the number of cities
n
from the input matrix and initialize an object of theUnionFind
class, which helps manage and track groups of connected cities.Use two loops to go through each unique pair of cities
(i, j)
wherei < j
. This ensures that the same pair is not checked twice.For each pair, check if the cities
i
andj
are directly connected by looking at the value ofcities[i][j]
.If
cities[i][j]
is1 , citiesi
andj
are directly connected.Use the
find
operation to find the subsets both cities belong to.If the cities belong to two different subsets, run the
union
operation on the cities i and j to merge their separate subsets into one subset. Also, decrease thecount
variable by1 , which tracks the number of provinces in theUnionFind
class, as merging the two subsets would reduce the total number of provinces.If the two cities belong to the same subset, skip them because they have already been connected.
Otherwise, move to the next city if
cities[i][j]
is0 because it means citiesi
andj
are not connected.
After going through all pairs of cities, return the
count
, containing the number of provinces.
Let’s look at the following illustration to get a better understanding of the solution: