How to Visualize a Graph for Competitive Programming (Edge Lists vs Adjacency Lists)
The problem gives you n nodes and m edges as a pile of number pairs. You read the sample test twice and still can’t say whether it has a cycle. Your code passes the sample and fails on test 4. Most of the time the fix starts with a picture. Learning to visualize a graph for competitive programming turns a wall of numbers into a shape you can reason about, and it makes the choice between an edge list and an adjacency list obvious.
This guide shows you how to read graph input, how each storage format works, when to pick which and how to draw a graph fast, by hand or with a tool. You’ll get C++ code, a worked example, the mistakes that cost contestants the most time and a checklist to run before you submit.
Why drawing the graph pays off
A graph is a shape, and numbers hide shapes. Once you draw one, a lot becomes visible at a glance. You see whether it’s a tree or has cycles, how many separate components it has, where the long paths run and which node sits in the middle of everything.
It also catches bugs early. If your adjacency list prints something that doesn’t match your drawing, you found the problem before the judge did. A two minute sketch on the sample test often saves twenty minutes of debugging.
Read the input format first
Before you draw anything, answer five questions from the statement:
- Are the edges directed or undirected? An undirected edge works in both directions.
- Are the nodes numbered from 0 or from 1? This one trips up more people than any algorithm.
- Do edges carry weights? If so, the input has a third number per line.
- Can the graph have self loops or repeated edges between the same pair?
- Is it guaranteed to be connected, or to be a tree? A tree has exactly n minus 1 edges and no cycles.
Also check the limits. If n goes up to 100000, you need a format that uses memory in proportion to the edges. If n is at most 500, you have more room to be lazy.
The edge list
An edge list stores each edge as a pair of nodes, one after the other. It’s exactly how most problems hand you the input, so storing it takes a few lines:
int n, m;
cin >> n >> m;
vector<pair<int, int>> edges(m);
for (auto &e : edges) {
cin >> e.first >> e.second;
}It uses memory in proportion to m, and it’s easy to sort, which matters for some algorithms. The weakness is lookup. To find the neighbors of one node, you scan the whole list.
Reach for an edge list when the algorithm loops over all edges anyway. Kruskal’s minimum spanning tree sorts the edges by weight and feeds them to a disjoint set union. Bellman Ford relaxes every edge in repeated passes. Both want a flat list of edges.
The adjacency list
An adjacency list keeps, for every node, a list of its neighbors. This is the default for most contest problems:
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}Notice the size of n plus 1. That leaves room for nodes numbered from 1. Notice the two push_back calls too. They exist because the graph is undirected. For a directed graph, keep only the first one.
With weights, store a pair in each slot. Use a vector of vectors of pairs, and push a neighbor and a weight together:
vector<vector<pair<int, int>>> adj(n + 1);
// inside the loop, after reading u, v and w
adj[u].push_back({v, w});
adj[v].push_back({u, w});The list takes memory in proportion to n plus m, and you can visit all neighbors of a node in time that matches their count. That’s why breadth first search, depth first search, Dijkstra, topological sort and tree dynamic programming all use it.
What about the adjacency matrix?
A matrix is an n by n table where cell (u, v) says whether an edge exists. Checking one edge takes constant time, which is the one thing lists can’t match.
The price is memory. With n equal to 100000, the table holds ten billion cells, about 40 gigabytes with 4 byte integers. No judge allows that. Use a matrix only when n is small, up to a few thousand, or when the graph is dense, and for algorithms like Floyd Warshall that need all pairs.
Which one should you pick?
Match the format to what the algorithm does most:
- Walk from node to node, as in BFS, DFS, Dijkstra or a topological sort. Use an adjacency list.
- Loop over every edge, as in Kruskal, Bellman Ford or a disjoint set union. Use an edge list.
- Ask “is there an edge between u and v?” many times on a small graph. Use a matrix.
- Need all pairs of shortest paths with n under about 500. Use a matrix.
Not sure? Start with the adjacency list. You can always build an edge list from the input too, and keeping both costs very little.
One graph in three forms
Take this small undirected graph with 5 nodes and 5 edges. The input looks like this:
5 5
1 2
1 3
2 4
3 4
4 5As an adjacency list, it becomes:
1: 2 3
2: 1 4
3: 1 4
4: 2 3 5
5: 4Now draw it. Put node 1 at the top, nodes 2 and 3 below it, node 4 under both and node 5 at the bottom. Right away you can see what the numbers hid. Nodes 1, 2, 4 and 3 form a cycle, so this isn’t a tree. Node 5 is a leaf that hangs off node 4. And node 4 has the highest degree, which makes it a likely bottleneck for shortest paths.
Run a quick sanity check as well. In an undirected graph, the sum of all degrees equals twice the number of edges. Here the degrees are 2, 2, 2, 3 and 1, which add up to 10, and twice 5 is 10.
How to draw a graph quickly
You have two routes, and the best contestants use both.
By hand, follow these steps:
- Write the node numbers as dots, spread out on the page.
- Draw one line per edge, taken straight from the edge list.
- For a directed graph, add an arrow to each line. For weights, write the number on the line.
- Move the dots until the lines stop crossing. A tree should hang from a root at the top.
- Mark anything the problem cares about, such as the start node, the target or special colors.
With a tool, paste your edges into our graph visualizer and look at the drawing. It’s faster than a pencil for graphs with more than a dozen nodes, and it’s the quickest way to check a test you generated yourself.
Draw your own small tests
The sample test is rarely the one that breaks you. Build tiny graphs that attack your own code: a single node, two nodes with no edge, a path, a star, a cycle, a graph with a repeated edge. Draw each one before you run it, so you know the right answer in advance.
Need random edges for a stress test? Our random number generator gives you node pairs fast. Run your solution and a slow brute force on the same input, then compare the two outputs with our text diff checker. When they differ, you have a small failing graph you can draw and study.
Mistakes that cost contestants points
These slips cause most wrong answers on graph problems:
- Mixing 0 based and 1 based numbering, then reading past the end of an array.
- Forgetting the second push_back on an undirected graph, so half the edges vanish.
- Using a matrix when n is large, which crashes on memory.
- Skipping the reset between test cases. Clear every list before you read the next graph.
- Recursing in DFS on a path with 200000 nodes. Depending on the judge, the stack runs out. Write the search with your own stack or a queue if depth can get that large.
- Ignoring repeated edges and self loops when the statement allows them.
- Treating the graph as connected when the statement never says so, and starting a search from one node only.
- Using an int for distances that can pass two billion. Use long long.
Debug with a printout that matches your drawing
When your answer is wrong, print the adjacency list in the same shape as the example above and hold it next to your drawing. Does every edge appear? Does it appear in both directions for an undirected graph? Does the degree sum match twice the edge count? Those three checks catch most input bugs in under a minute.
Got a big input file with odd lines? Test a pattern in our regex tester to find lines that don’t have exactly two numbers. And to count the lines in your test file against m, paste it into our character counter.
A checklist before you submit
Run through this list once:
- Directed or undirected, and do you store each edge the right number of times?
- Nodes start at 0 or 1, and is every array big enough?
- Weights, self loops and repeated edges are handled or ruled out.
- The storage format matches the algorithm and the limits.
- Every list resets between test cases.
- Deep recursion won’t overflow the stack.
- Distances use long long where they can grow large.
- You drew the sample test and your printout matches the drawing.
The short version
Read the input format first, then draw the sample test. Use an adjacency list when you walk from node to node, an edge list when you loop over every edge and a matrix only when n is small. Watch the numbering, store undirected edges twice and reset your lists for each test. A rough sketch of the graph catches more bugs than any amount of staring at numbers.
Open the last graph problem you got wrong and draw its sample test today. You may spot the bug in a minute.