Graphs
Build a Graph as an Adjacency List
Represent an undirected graph as a per-vertex list of neighbours. For every
edge (u, v), append v to adj[u] and u to adj[v]. Neighbour lists
keep insertion order so the graph is a stable, deterministic fixture for the
search lessons.
Algorithm
Basic Implementation
basic.cs
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[][] edges = { new int[] {1, 2}, new int[] {1, 3}, new int[] {2, 4}, new int[] {3, 4}, new int[] {4, 5}, new int[] {5, 6} };
Dictionary<int, List<int>> adj = new Dictionary<int, List<int>>();
foreach (int[] e in edges) {
if (!adj.ContainsKey(e[0])) adj[e[0]] = new List<int>();
if (!adj.ContainsKey(e[1])) adj[e[1]] = new List<int>();
adj[e[0]].Add(e[1]);
adj[e[1]].Add(e[0]);
}
List<int> keys = new List<int>(adj.Keys);
keys.Sort();
List<string> parts = new List<string>();
foreach (int v in keys) {
parts.Add(v + ": [" + string.Join(", ", adj[v]) + "]");
}
Console.WriteLine("{" + string.Join(", ", parts) + "}");
}
}
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
Dictionary<int, List<int>>maps eachintvertex key to a mutableList<int>neighbour list. TheContainsKeychecks and indexer writes create each list on first sight of a vertex; those list objects are managed references and their backing arrays are reclaimed by GC.- Edge insertion appends both directions with
List<int>.Add, so each neighbour list keeps the checked-in edge order visible in the trace. For printing, the code copiesadj.Keysto aList<int>and callsSort()so it does not depend onDictionaryhash-table enumeration order.
adjacency list
Each edge adds two directed entries, one in each direction.