




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.
1var findCircleNum = function(isConnected) {
2    const n = isConnected.length;
3    const visited = new Array(n).fill(false);
4    let provinces = 0;
5
6    const dfs = (node) => {
7        visited[node] = true;
8        for (let i = 0; i < n; i++) {
9            if (isConnected[node][i] === 1 && !visited[i]) {
10                dfs(i);
11            }
12        }
13    };
14
15    for (let i = 0; i < n; i++) {
16        if (!visited[i]) {
17            dfs(i);
18            provinces++;
19        }
20    }
21    return provinces;
22};In JavaScript, we initialize an array to track visited nodes. For each city, if not visited, we launch a DFS to mark all connected cities and increment the count of provinces.
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.