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.cpp
#include <iostream>
#include <vector>
#include <map>
int main() {
std::vector<std::pair<int, int>> edges = {
{1, 2}, {1, 3}, {2, 4}, {3, 4}, {4, 5}, {5, 6}};
std::map<int, std::vector<int>> adj;
for (const auto& e : edges) {
adj[e.first].push_back(e.second);
adj[e.second].push_back(e.first);
}
std::cout << "{";
bool first = true;
for (const auto& kv : adj) {
if (!first) std::cout << ", ";
std::cout << kv.first << ": [";
for (size_t i = 0; i < kv.second.size(); ++i) {
if (i > 0) std::cout << ", ";
std::cout << kv.second[i];
}
std::cout << "]";
first = false;
}
std::cout << "}" << std::endl;
return 0;
}
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- C++: a
std::map<int, std::vector<int>>keeps vertices in sorted order, and eachvectorstores neighbours appended 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.