Mid From PDF Coding C# Coding Interview

Number of connected components in undirected graph?

int CountConnectedComponents(Dictionary<int, List<int>> graph) {
var visited = new HashSet<int>();
int count = 0;

Follow on:

foreach (var node in graph.Keys) {
if (!visited.Contains(node)) {

DFS(node, graph, visited);

count++;

}
}
return count;
}

void DFS(int node, Dictionary<int, List<int>> graph, HashSet<int>

visited) {

visited.Add(node);

foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) {

DFS(neighbor, graph, visited);

}
}
}

Explanation:

Run DFS on unvisited nodes, count how many times DFS starts.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details