Computer Science and IT‹›⌂ 0:00 studied

Module 5 · 17 min read · Free chapter

Graphs and their representation

In short

A graph can be stored as an adjacency matrix, which takes Θ(V²) space and checks an edge in Θ(1), or as adjacency lists, which take Θ(V + E) space and suit sparse graphs. BFS uses a queue and DFS uses a stack, and both run in Θ(V + E) with lists. Degrees always add up to twice the number of edges.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: a railway map

Open a railway map of India. You see junctions such as Mughalsarai, Itarsi and Vijayawada, and lines joining them. To plan a journey, you do not care where a junction sits on the page; you care only which junctions are joined, and perhaps how long each line is.

That picture, with points and the lines between them, is a graph. The points are vertices and the lines are edges. If some lines allow travel in one direction only, like one-way streets, the graph is directed, and if each line carries a distance or a fare, it is weighted.

Graphs are everywhere once you look. Friends on a social network, web pages and their links, cities on a road map and tasks that must wait for other tasks are all graphs.

This chapter answers a data-structure question: how do we store a graph in memory, and how do we walk through it? The two great walks, breadth-first and depth-first search, turn out to be a queue and a stack in disguise.

Why it matters. A navigation app, a friend suggestion and a compiler's order of work all start by storing a graph well. Choosing the wrong representation can make the same program a thousand times slower or larger.

Graph vocabulary and degrees

A graph is written G=(V,E)G = (V, E), where VV is the set of vertices and EE the set of edges. In this chapter VV and EE also stand for their counts when used inside a bound such as Θ(V+E)\Theta(V + E). A simple graph has no self-loops and no repeated edges, which is the usual assumption in exam questions.

In an undirected graph an edge {u,v}\{u, v\} joins uu and vv both ways, and uu and vv are adjacent. In a directed graph an edge (u,v)(u, v) goes from its tail uu to its head vv only. A weighted graph attaches a number to each edge, such as a distance, a cost or a capacity.

How many edges can there be? Each of the nn vertices can join each of the other n−1n - 1, and each undirected edge is counted twice that way, so a simple undirected graph has at most n(n−1)2\dfrac{n(n-1)}{2} edges. A simple directed graph can have both (u,v)(u, v) and (v,u)(v, u), so it has at most n(n−1)n(n-1).

The degree of a vertex in an undirected graph is the number of edges touching it. Every edge adds 11 to the degree of each of its two ends, which gives the handshake lemma:

∑v∈Vdeg⁡(v)=2e\sum_{v \in V} \deg(v) = 2e

So the sum of degrees is always even, and the number of vertices with odd degree must be even. In a directed graph each vertex has an in-degree and an out-degree, and both kinds add up to ee, because each edge has one tail and one head.

Worked example. A graph on vertices A to H has the edges A–B, A–C, B–D, C–D, C–E, E–F and G–H. The degrees are 2, 2, 3, 2, 2, 1, 1 and 1, whose sum is 14=2×714 = 2 \times 7. The odd-degree vertices are C, F, G and H, four of them, which is even as the lemma demands.

Why it matters. Degree counting answers many quick GATE questions, such as whether a graph with given degrees can exist. The deeper theory of paths, colouring and matching is covered in graph theory, while this chapter focuses on storage and traversal.

Adjacency matrix versus adjacency list

The adjacency matrix of a graph on vertices 00 to V−1V - 1 is a V×VV \times V array AA with auv=1a_{uv} = 1 if (u,v)(u, v) is an edge and 00 otherwise. For a weighted graph the entry holds the weight, with 00 or ∞\infty marking "no edge". For an undirected graph the matrix is symmetric, auv=avua_{uv} = a_{vu}, so only one triangle really needs storing.

The adjacency list keeps, for each vertex, a linked list of its neighbours. An undirected edge appears twice, once in each end's list, so there are 2E2E entries, while a directed edge appears once. In C the list version looks like this.

struct edge { int to; struct edge *next; };
struct edge *adj[MAXV];               /* adj[u] heads u's neighbour list */
void add_edge(int u, int v) {         /* undirected: store both ways */
    struct edge *p = malloc(sizeof *p);
    p->to = v; p->next = adj[u]; adj[u] = p;
    p = malloc(sizeof *p);
    p->to = u; p->next = adj[v]; adj[v] = p;
}

The matrix version is simply int a[MAXV][MAXV]; with a[u][v] = a[v][u] = 1 for each edge. The table compares the two for the operations that matter.

Operation Adjacency matrix Adjacency list
Space Θ(V2)\Theta(V^2) Θ(V+E)\Theta(V + E)
Is (u, v) an edge? Θ(1)\Theta(1) Θ(deg⁡u)\Theta(\deg u)
List all neighbours of u Θ(V)\Theta(V) Θ(deg⁡u)\Theta(\deg u)
Add an edge Θ(1)\Theta(1) Θ(1)\Theta(1)
Visit the whole graph (BFS or DFS) Θ(V2)\Theta(V^2) Θ(V+E)\Theta(V + E)

Worked example. A road graph has V=104V = 10^4 junctions and E=5×104E = 5 \times 10^4 roads. The matrix needs 10810^8 cells, while the lists need about 104+2×5×104=1.1×10510^4 + 2 \times 5 \times 10^4 = 1.1 \times 10^5 entries, roughly 900900 times fewer. Most real graphs are like this, with EE far below V2V^2, so lists are the usual choice.

The matrix still wins in two cases. When the graph is dense, with EE close to V2V^2, the list saves nothing and costs pointers. And when the main question is "is there an edge between uu and vv?", the matrix answers in one step.

Why it matters. The same algorithm, run on the two representations, can differ by orders of magnitude in time and memory. GATE asks this comparison directly, and it also hides it inside questions on BFS, DFS and shortest paths.

Incidence matrix, edge list and what the matrix can count

Two more representations appear in exams. The incidence matrix is a V×EV \times E array with one row per vertex and one column per edge. In an undirected graph each column has exactly two 1s, at the two ends of its edge, so the sum of a row is the degree of that vertex and the sum of the whole matrix is 2E2E.

For a directed graph the two ends of each column are marked +1+1 and −1-1. Which sign goes on the tail is only a convention, so read it from the question. The incidence matrix needs Θ(V⋅E)\Theta(V \cdot E) space, which is usually more than either the adjacency matrix or the lists.

The edge list simply stores the EE pairs, or triples with weights, in an array. It takes Θ(E)\Theta(E) space and is ideal when an algorithm wants to look at edges in order of weight, as Kruskal's minimum spanning tree method does. But finding the neighbours of one vertex then needs a scan of all EE edges.

What the adjacency matrix can count. Multiplying the matrix by itself counts walks. The entry (A2)ij(A^2)_{ij} equals the number of walks of length 22 from ii to jj, because each such walk passes through some middle vertex kk with aik=akj=1a_{ik} = a_{kj} = 1. In the same way (Ak)ij(A^k)_{ij} counts walks of length kk.

For an undirected simple graph, the diagonal entry (A3)ii(A^3)_{ii} counts closed walks of length 33 from ii, that is triangles through ii, each counted twice for the two directions. Each triangle has three corners, so the graph has trace⁡(A3)6\dfrac{\operatorname{trace}(A^3)}{6} triangles. For example, K4K_4, the complete graph on four vertices, has trace 2424 and so 44 triangles.

Dense or sparse? A graph is called sparse when EE is close to VV and dense when EE is close to V2V^2. Road and rail networks are sparse, since a junction meets only a few lines, while a table of distances between every pair of cities is dense.

Why it matters. GATE sometimes gives a matrix and asks for the number of edges, the degrees or the number of triangles. Knowing what each representation reveals at a glance turns these into one-line answers.

Breadth-first search: a graph walk with a queue

Breadth-first search (BFS) explores a graph in rings. It visits the source first, then all vertices one edge away, then all vertices two edges away, and so on. A queue produces exactly this order, because vertices found first are explored first.

void bfs(int s) {
    int q[MAXV], front = 0, rear = 0;
    visited[s] = 1; q[rear++] = s;
    while (front < rear) {
        int u = q[front++];
        printf("%d ", u);
        for (struct edge *p = adj[u]; p != NULL; p = p->next)
            if (!visited[p->to]) { visited[p->to] = 1; q[rear++] = p->to; }
    }
}

A vertex is marked visited when it enters the queue, not when it leaves, so that no vertex is queued twice. Every vertex enters and leaves the queue once, and every adjacency list is scanned once. So with lists BFS takes Θ(V+E)\Theta(V + E) time, while with a matrix the scan of each row costs Θ(V)\Theta(V) and the total is Θ(V2)\Theta(V^2).

Worked example. Run BFS from A on the graph with edges A–B, A–C, B–D, C–D, C–E and E–F, taking neighbours in alphabetical order. The queue starts as A; removing A adds B and C; removing B adds D; removing C adds E, since D is already marked; removing D adds nothing; removing E adds F. The visit order is A B C D E F.

The BFS also gives each vertex its level, the number of edges on the shortest path from A. Here A is at level 00, B and C at level 11, D and E at level 22, and F at level 33. So in an unweighted graph BFS finds shortest paths by number of edges, and the edges used to discover each vertex form a BFS tree.

When edges carry different weights, BFS no longer gives shortest distances, and a priority queue takes the place of the plain queue. Those weighted algorithms are taught in graph algorithms.

Why it matters. BFS powers "people you may know" at distance two, the fewest-hops route in a network, and the level-order walk of a tree. GATE often gives a graph and asks which of four orders is a valid BFS order, so practise checking whether each level is finished before the next begins.

Depth-first search: a graph walk with a stack

Depth-first search (DFS) behaves like a person exploring a maze with a ball of thread. It goes from the current vertex to an unvisited neighbour, and from there to another, as deep as possible. Only at a dead end does it back up to the last vertex that still has an unvisited neighbour.

void dfs(int u) {
    visited[u] = 1; printf("%d ", u);
    for (struct edge *p = adj[u]; p != NULL; p = p->next)
        if (!visited[p->to]) dfs(p->to);
}

The "backing up" is a stack. In the recursive version it is the call stack, and an iterative version pushes vertices on an explicit stack. Each vertex is visited once and each list scanned once, so DFS also takes Θ(V+E)\Theta(V + E) with lists and Θ(V2)\Theta(V^2) with a matrix.

Worked example. Run DFS from A on the same graph, again in alphabetical order. From A it goes to B, from B to D, from D to C (since B is done), and from C, whose neighbours A and D are visited, on to E and then F. The order is A B D C E F, quite different from the BFS order A B C D E F.

DFS records two times for each vertex: the discovery time when it is first reached and the finish time when its list is exhausted. These intervals nest like brackets, which leads to a classification of every edge (u,v)(u, v) in a directed graph:

  • A tree edge discovers vv for the first time.
  • A back edge goes to an ancestor of uu that is still on the stack.
  • A forward edge goes to a descendant of uu that is already finished.
  • A cross edge goes to a vertex in another, already finished, branch.

A directed graph has a cycle exactly when DFS finds a back edge. In an undirected graph only tree edges and back edges can occur, and any back edge, such as C–A in the example, closes a cycle, here A–B–D–C–A. The finish times also give a topological order of a graph without cycles.

Why it matters. DFS detects cycles, finds connected parts and orders tasks that depend on each other. Exams ask for a DFS order, the discovery and finish times, or the type of a given edge, and all three come from tracing the stack carefully.

Connected components

An undirected graph is connected if there is a path between every pair of vertices. Otherwise it falls into separate pieces called connected components, each connected on its own with no edge between pieces. The example graph has two components: A, B, C, D, E, F in one, and G, H in the other.

BFS or DFS finds them at once. Loop over the vertices, and each time you meet an unvisited one, start a new traversal from it and give every vertex it reaches the same component number. The number of traversals started is the number of components, and the total time is still Θ(V+E)\Theta(V + E), because each vertex and edge is handled once overall.

Some counting facts about components come up often:

  • A connected graph on nn vertices needs at least n−1n - 1 edges, and a tree has exactly n−1n - 1.
  • A forest, a graph with no cycles, on nn vertices with kk components has exactly n−kn - k edges.
  • A simple graph on nn vertices with kk components has at most (n−k)(n−k+1)2\dfrac{(n-k)(n-k+1)}{2} edges, reached by one complete piece on n−k+1n - k + 1 vertices and k−1k - 1 lone vertices.
  • Any simple graph on nn vertices with more than (n−1)(n−2)2\dfrac{(n-1)(n-2)}{2} edges must be connected.

Worked example. A simple graph has 1010 vertices and 33 components. Its largest possible number of edges is (10−3)(10−3+1)2=7×82=28\dfrac{(10-3)(10-3+1)}{2} = \dfrac{7 \times 8}{2} = 28. And since 9×82=36\dfrac{9 \times 8}{2} = 36, any simple graph on 1010 vertices with 3737 or more edges is surely connected.

For directed graphs the idea splits in two. A directed graph is strongly connected if every vertex can reach every other along the arrows, and its strongly connected components are found with two DFS passes, as shown in graph algorithms.

Why it matters. Components tell a network engineer which computers can talk, and an image program which pixels form one object. GATE asks both the component count after a traversal and the edge-count bounds above, often in one numerical.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about graphs in four ways:

  1. They ask you to define graph terms and to draw the adjacency matrix and lists of a given graph.
  2. They ask you to compare the representations for space and for common operations, and to say which suits a given application.
  3. They ask you to trace BFS and DFS from a vertex, showing the queue or stack at each step.
  4. They ask you to use a traversal for a task, such as counting components or detecting a cycle.

Practice questions (our own, not previous-year questions).

  1. Define degree, in-degree and out-degree, and prove that the number of odd-degree vertices in any graph is even. (10 marks)
  2. For the graph with edges A–B, A–C, B–D, C–D, C–E and E–F, draw the adjacency matrix and adjacency lists, and compare their space. (10 marks)
  3. Explain BFS and DFS with the data structure each uses, trace both from A on the graph of question 2, and state their time complexity for each representation. (15 marks)

Answer plan for question 3.

  • Begin by stating that both methods visit every reachable vertex once and differ only in the order of visiting.
  • Explain that BFS uses a queue and visits vertices by distance, so it gives shortest paths by edge count in unweighted graphs.
  • Trace BFS from A with the queue after each step, ending with the order A B C D E F and the levels 0, 1, 1, 2, 2, 3.
  • Explain that DFS uses a stack, through recursion or explicitly, and goes deep before backtracking.
  • Trace DFS from A with the stack after each step, ending with the order A B D C E F, and point out the back edge C–A that reveals a cycle.
  • State that both take Θ(V+E)\Theta(V + E) with adjacency lists and Θ(V2)\Theta(V^2) with an adjacency matrix, and say why.
  • Conclude with one use of each, such as fewest-hop routing for BFS and cycle detection for DFS.

Quick revision

  • A simple undirected graph on nn vertices has at most n(n−1)2\dfrac{n(n-1)}{2} edges, and a simple directed one at most n(n−1)n(n-1).
  • The degrees of an undirected graph add up to 2e2e, so the odd-degree vertices are even in number.
  • An adjacency matrix takes Θ(V2)\Theta(V^2) space and tests an edge in Θ(1)\Theta(1).
  • Adjacency lists take Θ(V+E)\Theta(V + E) space, with 2E2E entries for an undirected graph.
  • An incidence matrix is V×EV \times E, with two 1s per column in an undirected graph.
  • (A2)ij(A^2)_{ij} counts walks of length 22, and an undirected simple graph has trace⁡(A3)6\dfrac{\operatorname{trace}(A^3)}{6} triangles.
  • BFS uses a queue, visits by levels and gives shortest edge-count paths in unweighted graphs.
  • DFS uses a stack, and a back edge in DFS means a cycle.
  • BFS and DFS take Θ(V+E)\Theta(V + E) with lists and Θ(V2)\Theta(V^2) with a matrix.
  • The number of traversal starts equals the number of connected components, and a forest has n−kn - k edges.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. The largest number of edges in a simple undirected graph on nn vertices is:

  2. An undirected graph has 77 edges. The sum of the degrees of its vertices is:

  3. Which degree sequence can NOT belong to any simple undirected graph?

  4. The space needed by an adjacency matrix of a graph with VV vertices is:

  5. For an undirected simple graph with adjacency matrix AA, the number of triangles equals:

  6. The adjacency lists of an undirected graph with EE edges contain how many entries in total?

  7. For a sparse graph, which operation is FASTER on an adjacency matrix than on adjacency lists?

  8. In the incidence matrix of an undirected graph without self-loops, each column contains:

  9. Breadth-first search is naturally implemented with a:

  10. Edges A–B, A–C, B–D, C–D, C–E, E–F; BFS from A in alphabetical order. The visit order is:

  11. BFS on a graph with VV vertices and EE edges stored as an adjacency matrix takes:

  12. On the same graph, DFS from A in alphabetical order visits:

  13. A directed graph contains a cycle if and only if its DFS finds a:

  14. A simple graph has 1010 vertices and 33 connected components. The largest possible number of edges is:

  15. A forest has 1212 vertices and 44 components. How many edges does it have?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

When is an adjacency matrix better than an adjacency list?

For dense graphs, and when the main task is checking whether a given edge exists, which the matrix does in Θ(1).

Which data structures do BFS and DFS use?

BFS uses a queue and visits vertices level by level; DFS uses a stack, often the recursion stack, and goes deep first.

What is the handshake lemma?

In an undirected graph the sum of all degrees equals twice the number of edges, so odd-degree vertices come in an even number.

How are connected components counted?

Start a new BFS or DFS from every vertex not yet visited; the number of starts is the number of components.

More in this module: Data structures

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): graphs, BFS and DFS