Graph Theory37 sections · 1633 units
Open in Course

Explaining the Syntax

vector adj[N]

vector<int> adj[5] creates 55 separate vectors. Each adj[i] holds the neighbors of node ii.

1.1. adj[0] is a vector that stores neighbors of node 00.

2.2. adj[1] is a vector that stores neighbors of node 11.

3.3. And so on for adj[2], adj[3], adj[4]. If Node 11 connects to nodes 22 and 33, then adj[1] = {2, 3}. To add a neighbor, use adj[u].push_back(v). To iterate through all neighbors of node uu, loop through adj[u]. This two-line pattern is the foundation of every graph algorithm you will write. Learn it now because you will use it hundreds of times.