Graphs
Shortest Path (Unweighted, via BFS)
BFS explores a graph layer by layer, so the first time it reaches a vertex
is along a shortest path. Track dist[v] and parent[v] while exploring,
then walk parents back from the target to reconstruct the route.
Algorithm
On the canonical graph from graph-adjacency-list, the shortest path from
1 to 6 is [1, 2, 4, 5, 6] with distance 4. The path is rebuilt from
parent: 6 -> 5 -> 4 -> 2 -> 1, reversed.
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 src = 1;
int dst = 6;
Dictionary<int, int> dist = new Dictionary<int, int>();
Dictionary<int, int> parent = new Dictionary<int, int>();
dist[src] = 0;
parent[src] = 0;
Queue<int> queue = new Queue<int>();
queue.Enqueue(src);
while (queue.Count > 0) {
int v = queue.Dequeue();
foreach (int nb in adj[v]) {
if (!dist.ContainsKey(nb)) {
dist[nb] = dist[v] + 1;
parent[nb] = v;
queue.Enqueue(nb);
}
}
}
List<int> path = new List<int>();
int node = dst;
while (node != 0) {
path.Add(node);
node = parent[node];
}
path.Reverse();
Console.WriteLine("[" + string.Join(", ", path) + "]");
Console.WriteLine(dist[dst]);
}
}
Complexity
- Time: O(V + E)
- Space: O(V)
Implementation notes
- C#: a
distdictionary doubles as the visited check,parentrecords predecessors (0 marks the source), and aQueue<int>gives FIFO order. - The replay shows
dist,parent, and the queue filling in, then the reconstructed path, matching the lesson spec.
layers equal distance
BFS order equals distance in an unweighted graph.