Adjacency List

I was learning some graph theory algorithms and implemented them using adjacency list.
But recently when I tried to print the adjacency list itself I was unable to do so with a lot many errors coming my way.

It would be of great help if you could suggest the correct code for the purpose which is easy to understand as well as implement, and does not use things like structs and classes.

you could use list also instead of vector

Thanks for the answer. But this will only work in case of non-directed graphs whereas I want to print the adjacency list for a DAG.

Just use a vector of vectors. Let’s say you have n vertices.
Step 1. Create a vector that will store adjacency lists for each vertex.
vector<vector> adj(n);
Step 2. Add edges of the graph.
Let’s say there is an edge directed from vertex u to vertex v. Then:
adj[u].push_back(v);
Step 3. (for undirected)
If your graph is directed then that’s it, but if it’s undirected then also add in the other direction:
adj[v].push_back(u);
Let me know if something is unclear.

1 Like