


n = 4, roads = [ [1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 1] ]

So, there are ‘2’ provinces.
1. A city is connected to itself. So, for every city ‘i’, ‘roads[i][i] = 1’.
The first line contains an integer ‘n’ denoting the number of cities.
Next ‘n’ lines contains ‘n’ space-separated integers denoting a row of ‘roads’.
The output contains the number of provinces.
You do not need to print anything, it has already been taken care of. Just implement the given function.
Disjoint-set (or Union-find) is a data structure that stores a collection of disjoint (non-overlapping) sets. This data structure consists of three basic operations:
The idea is to use a Disjoint-set 'DS’, which initially stores ‘n’ sets, each containing a single city. After that, for each pair of cities ‘i’ and ‘j’ that are connected by a road (i.e., ‘ROADS[i][j] = 1’), we merge the two sets containing these cities by calling ‘unionSet(i, j)’. Finally, the number of provinces will be equal to the number of sets in 'DS’.
Consider the given city network as an undirected graph. So, the number of provinces is equal to the number of connected components in the graph. We can find the connected components by performing a Breadth-first search (BFS) traversal starting from every unvisited node. Each BFS traversal will mark each node in a connected component as visited, so the number of connected components is equal to BFS traversals.
Consider the given city network as an undirected graph. So, the number of provinces is equal to the number of connected components in the graph. We can find the connected components by performing a Depth-first search (DFS) traversal starting from every unvisited node. Each DFS traversal will mark each node in a connected component as visited, so the number of connected components is equal to the number of DFS traversals.
The ‘dfs(integer V)’ function: