Intermediate·Concept·2 min read

Graphs in C#

Practice this question

Problems to practice

  • Number of Islands
  • Course Schedule
  • Clone Graph
  • Topological Sort
  • BFS and DFS traversal
  • Shortest path in unweighted graph
  • Union-Find connectivity

Example: BFS using queue

csharp
var queue = new Queue<int>();
var visited = new HashSet<int>();
queue.Enqueue(start);
visited.Add(start);

while (queue.Count > 0) {
    int node = queue.Dequeue();
    foreach (var neighbor in graph[node]) {
        if (!visited.Contains(neighbor)) {
            visited.Add(neighbor);
            queue.Enqueue(neighbor);
        }
    }
}

Adapted from 17_DSA_DOTNET.md · “9. Graphs in C#”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.