Graph Theory37 sections · 1633 units
Open in Course

Adding Undirected Edges

Code Snippet

When the input says there is an undirected edge between uu and vv, you must record it in both adjacency lists. I add vv to adj[u] and uu to adj[v].

adj[u].push_back(v)
adj[v].push_back(u)

If you only add one direction, a traversal from the other endpoint will miss the connection and you will report the wrong answer. Adding both entries takes O(1)O(1) time and O(1)O(1) extra space per edge, so you should always do it.