A graph is a set of nodes — cities, people, cells — and the links between them: roads, friendships. It is easy to picture and takes a moment to encode. The usual way: for each node, list who it connects to.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 5;
vector<vector<int>> adj(n);
// undirected edges
adj[0].push_back(1); adj[1].push_back(0);
adj[0].push_back(2); adj[2].push_back(0);
adj[1].push_back(3); adj[3].push_back(1);
for (int v = 0; v < n; v++) {
cout << v << ":";
for (int to : adj[v]) cout << " " << to;
cout << endl;
}
return 0;
}0: 1 2 1: 0 3 2: 0 3: 1 4:
//LINE BY LINE
Watch it run
There are five nodes. So far nothing joins any of them.
Two ways to store a graph
An adjacency LIST is the contest standard. An adjacency MATRIX is easier to write but will not fit in memory once there are many nodes.
| List | Matrix | |
|---|---|---|
| Санах ой / Memory | цэг + холбоос / nodes + edges | цэг² / nodes² |
| «a–b холбоотой юу?» / "is a joined to b?" | Удаан / slow | Шууд / instant |
| Хөршүүдээр явах / Walking neighbours | Хурдан / fast | Бүх цэгийг шалгана / checks every node |
| 10 000 цэг / 10 000 nodes | Асуудалгүй / fine | 100 сая нүд — багтахгүй / 100 million cells — too big |
When in doubt, use the list. Nearly every graph algorithm asks "the neighbours of this node", which is exactly what a list is for.
The graph hiding in the problem
A problem may never use the word "graph". If two things are CONNECTED to each other, it is one.
| In the problem | Node | Edge |
|---|---|---|
| Хот, зам / Cities and roads | Хот / a city | Зам / a road |
| Найзууд / Friendships | Хүн / a person | Найз байх / being friends |
| Лабиринт / A maze | Нүд / a cell | Хажуугийн нүд рүү / a step to a neighbour |
| Хичээлийн дараалал / Course order | Хичээл / a course | Урьдчилсан нөхцөл / a prerequisite |
Grid problems are graphs in disguise. Every cell is a node and every neighbour an edge — which is why BFS works on a grid unchanged.