Graphs
Build a Graph as an Adjacency List
Represent an undirected graph as a map from each vertex to its 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
The canonical fixture is 6 vertices [1..6] with undirected edges
(1,2), (1,3), (2,4), (3,4), (4,5), (5,6) inserted in that order. The
final adjacency list is
{1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3, 5], 5: [4, 6], 6: [5]}.
This same graph drives graph-bfs, graph-dfs, and
graph-shortest-path-bfs.
Basic Implementation
Basic.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Basic {
public static void main(String[] args) {
int[][] edges = {{1, 2}, {1, 3}, {2, 4}, {3, 4}, {4, 5}, {5, 6}};
Map<Integer, List<Integer>> adj = new LinkedHashMap<>();
for (int[] e : edges) {
adj.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]);
adj.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]);
}
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<Integer, List<Integer>> en : adj.entrySet()) {
if (!first) sb.append(", ");
sb.append(en.getKey()).append(": ").append(en.getValue());
first = false;
}
sb.append("}");
System.out.println(sb);
}
}
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- Java: a
LinkedHashMap<Integer, List<Integer>>keeps vertex insertion order, andcomputeIfAbsentappends neighbours in edge order. - The replay shows the adjacency map after each edge is added, matching the lesson spec.
adjacency list
Each edge adds two directed entries, one in each direction.