Problem Statement: You are given an undirected graph with V
vertices, represented as an adjacency list. Two nodes u
and v
belong to the same province if there is a path from u
to v
or vice versa. Your task is to determine how many such provinces (connected components) exist in the graph.
Number of Provinces - Using Graph Traversal - Visualization
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#define N 3
void dfs(int graph[N][N], int visited[N], int node) {
visited[node] = 1;
for (int i = 0; i < N; i++) {
if (graph[node][i] && !visited[i]) {
dfs(graph, visited, i);
}
}
}
int findProvinces(int graph[N][N]) {
int visited[N] = {0};
int provinces = 0;
for (int i = 0; i < N; i++) {
if (!visited[i]) {
dfs(graph, visited, i);
provinces++;
}
}
return provinces;
}
int main() {
int graph[N][N] = {
{1, 1, 0},
{1, 1, 0},
{0, 0, 1}
};
printf("Provinces: %d\n", findProvinces(graph));
return 0;
}
Time Complexity
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | If all nodes are part of one province, DFS/BFS will still touch all nodes and edges once. |
Average Case | O(V + E) | Each component is visited once, processing all its vertices and edges. |
Worst Case | O(V + E) | When all nodes are isolated, we perform V DFS/BFS calls with no edge visits. |
Comments
Loading comments...