⬅ Previous Topic
Depth-First Search in GraphsNext Topic ⮕
Connected Components in a Matrix⬅ Previous Topic
Depth-First Search in GraphsNext Topic ⮕
Connected Components in a MatrixTopic Contents
Given an undirected graph with V
vertices represented as an adjacency matrix isConnected
, a province is a group of directly or indirectly connected cities (vertices). A city is connected to itself.
Your task is to determine the total number of such provinces (i.e., the number of connected components in the graph).
provinceCount = 0
.i
from 0 to V-1:visited[i]
is false:i
.provinceCount
.provinceCount
.function findCircleNum(isConnected) {
const n = isConnected.length;
const visited = new Array(n).fill(false);
function dfs(city) {
for (let neighbor = 0; neighbor < n; neighbor++) {
if (isConnected[city][neighbor] === 1 && !visited[neighbor]) {
visited[neighbor] = true;
dfs(neighbor);
}
}
}
let provinces = 0;
for (let i = 0; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
dfs(i);
provinces++;
}
}
return provinces;
}
console.log("Provinces:", findCircleNum([[1,1,0],[1,1,0],[0,0,1]])); // Output: 2
console.log("Provinces:", findCircleNum([[1,0,0],[0,1,0],[0,0,1]])); // Output: 3
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even if all cities are in a single province, DFS/BFS will still visit all vertices and edges to ensure full connectivity. |
Average Case | O(V + E) | Each node and edge is visited once across all connected components using DFS or BFS. |
Worst Case | O(V + E) | In the worst case (e.g., each city is isolated), we still visit every node and no edges, resulting in a traversal of size V. |
O(V)
Explanation: A visited array of size V is required to track which cities have already been checked during traversal.
⬅ Previous Topic
Depth-First Search in GraphsNext Topic ⮕
Connected Components in a MatrixYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.