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.
A province is a connected component. The matrix tells which cities share an edge, so DFS or BFS from each unseen city paints one component.
Scan cities, start a DFS at every unvisited index, and increment the answer. The visited array visits each city once.
We create an array \(\textit{vis}\) to record whether each city has been visited.
Next, we traverse each city \(i\). If the city has not been visited, we start a depth-first search from that city. Using the matrix \(\textit{isConnected}\), we find the cities directly connected to this city. These cities and the current city belong to the same province. We continue the depth-first search for these cities until all cities in the same province have been visited. This counts as one province, so we increment the answer \(\textit{ans}\) by \(1\). Then, we move to the next unvisited city and repeat the process until all cities have been traversed.
Finally, return the answer.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of cities.
DFS needs a recursion stack and a visited array. Union-find merges along edges: start with \(n\) components and decrement when an edge joins two roots.
Iterate the upper triangle to avoid duplicate edges. Path compression keeps finds cheap. The remaining roots are the provinces.
We can also use the union-find data structure to maintain each connected component. Initially, each city belongs to a different connected component, so the number of provinces is \(n\).
Next, we traverse the matrix \(\textit{isConnected}\). If there is a connection between two cities \((i, j)\) and they belong to two different connected components, they will be merged into one connected component, and the number of provinces is decremented by \(1\).
Finally, return the number of provinces.
The time complexity is \(O(n^2 \times \log n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of cities, and \(\log n\) is the time complexity of path compression in the union-find data structure.