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.dart
void main() {
final edges = [[1, 2], [1, 3], [2, 4], [3, 4], [4, 5], [5, 6]];
final adj = <int, List<int>>{};
for (final e in edges) {
adj.putIfAbsent(e[0], () => []).add(e[1]);
adj.putIfAbsent(e[1], () => []).add(e[0]);
}
final parts = <String>[];
for (final v in adj.keys) {
parts.add('$v: [${adj[v]!.join(', ')}]');
}
print('{${parts.join(', ')}}');
}
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- Dart: a
Map<int, List<int>>(LinkedHashMap) preserves insertion order;putIfAbsentappends neighbours in edge order. - The replay shows the adjacency list after each edge is added, matching the lesson spec.
adjacency list
Each edge adds two directed entries, one in each direction.