




Sponsored
Sponsored
This approach uses Depth-First Search (DFS) to count the number of provinces. The core idea is to treat the connected cities as a graph and perform a DFS traversal starting from each city. During traversal, mark all reachable cities from the starting city. Each starting city for a DFS that visits new cities indicates the discovery of a new province.
Time Complexity: O(n^2), as we may visit each cell in the matrix.
Space Complexity: O(n) for the visited array.
1def findCircleNum(isConnected: List[List[int]]) -> int:
2    def dfs(node):
3        visited.add(node)
4        for i in range(len(isConnected)):
5            if isConnected[node][i] == 1 and i not in visited:
6                dfs(i)
7    
8    n = len(isConnected)
9    visited = set()
10    provinces = 0
11    for i in range(n):
12        if i not in visited:
13            dfs(i)
14            provinces += 1
15    return provincesThe Python solution also leverages DFS. A set is used to keep track of visited nodes (cities). For each city, if it is not in the visited set, a DFS is triggered marking all reachable cities along with counting a new province.
This approach employs the Union-Find (Disjoint Set Union) algorithm to find the number of provinces. This algorithm efficiently handles dynamic connectivity queries. By iteratively checking connections and performing unions, we can identify distinct connected components (provinces).
Time Complexity: O(n^2 * α(n)), where α is the inverse Ackermann function representing nearly constant time for union-find operations.
Space Complexity: O(n), the space for parent and rank arrays.
1
This Java solution features a Union-Find class with union and find operations. Upon establishing connections, cities are grouped under unique leaders using union sets and path compression. Provinces correspond to the count of unique root nodes.