Graphs
Breadth-First Search
From a start vertex, explore the graph layer by layer. Use a queue and a "visited" set. Dequeue a vertex, visit it, enqueue all unvisited neighbours.
Algorithm
Canonical adjacency list:
1 -> [2, 3]
2 -> [1, 4]
3 -> [1, 4]
4 -> [2, 3, 5]
5 -> [4, 6]
6 -> [5]
Starting at vertex 1, the BFS visit order is [1, 2, 3, 4, 5, 6].
Basic Implementation
basic.cs
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<int, List<int>> adj = new Dictionary<int, List<int>>();
adj[1] = new List<int> { 2, 3 };
adj[2] = new List<int> { 1, 4 };
adj[3] = new List<int> { 1, 4 };
adj[4] = new List<int> { 2, 3, 5 };
adj[5] = new List<int> { 4, 6 };
adj[6] = new List<int> { 5 };
int start = 1;
HashSet<int> visited = new HashSet<int>();
visited.Add(start);
Queue<int> queue = new Queue<int>();
queue.Enqueue(start);
List<int> order = new List<int>();
while (queue.Count > 0) {
int v = queue.Dequeue();
order.Add(v);
List<int> neighbours = adj[v];
for (int i = 0; i < neighbours.Count; i++) {
int nb = neighbours[i];
if (!visited.Contains(nb)) {
visited.Add(nb);
queue.Enqueue(nb);
}
}
}
Console.WriteLine("[" + string.Join(", ", order) + "]");
}
}
Complexity
- Time: O(V + E)
- Space: O(V)
Implementation notes
- C#:
Dictionary<int, List<int>>is the idiomatic adjacency list and keeps the vertex iteration shape visible; the lesson keeps the queue as a plainQueue<int>rather than reaching forChannel<T>or any async wrapper. - A
HashSet<int>is the explicit "visited" set; the queue is a plainQueue<int>withDequeueandEnqueue. - The replay prints the dequeued vertex, the queue, the visited set, and the running visit order each frame.
queue
A `Queue<int>` with `Enqueue` / `Dequeue` implements FIFO without hiding the iteration shape.
visited-before-enqueue
Mark a vertex visited before pushing it onto the queue. Keeps the queue size bounded by V.