




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.
1#include <vector>
2
3void dfs(int node, std::vector<std::vector<int>>& isConnected, std::vector<bool>& visited) {
4    visited[node] = true;
5    for (int i = 0; i < isConnected.size(); i++) {
6        if (isConnected[node][i] == 1 && !visited[i]) {
7            dfs(i, isConnected, visited);
8        }
9    }
10}
11
12int findCircleNum(std::vector<std::vector<int>>& isConnected) {
13    int n = isConnected.size();
14    std::vector<bool> visited(n, false);
15    int provinces = 0;
16    for (int i = 0; i < n; i++) {
17        if (!visited[i]) {
18            dfs(i, isConnected, visited);
19            provinces++;
20        }
21    }
22    return provinces;
23}Using C++, we employ a vector for tracking visited cities and perform DFS similarly to the C solution. For each unvisited city, we invoke the dfs function to mark all connected cities. The main function increments the province count for each fresh DFS traversal.
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
JavaScript implementation revolves around using the Union-Find structure to manage relationships between nodes. By uniting connected nodes, we condense the network into minimal root representations, each one indicating a separate province.