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

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.lua
local edges = {{1, 2}, {1, 3}, {2, 4}, {3, 4}, {4, 5}, {5, 6}}
local adj = {}
for _, e in ipairs(edges) do
	local u = e[1]
	local v = e[2]
	if adj[u] == nil then adj[u] = {} end
	if adj[v] == nil then adj[v] = {} end
	adj[u][#adj[u] + 1] = v
	adj[v][#adj[v] + 1] = u
end
io.write("{")
for v = 1, 6 do
	if v > 1 then io.write(", ") end
	io.write(v .. ": [")
	for k = 1, #adj[v] do
		if k > 1 then io.write(", ") end
		io.write(tostring(adj[v][k]))
	end
	io.write("]")
end
io.write("}\n")

Complexity

  • Build: O(V + E)
  • Space: O(V + E)

Implementation notes

  • Lua: a table maps each vertex to a sequence of neighbours; vertices 1..6 are printed in 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.