Mid Coding

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