Skip to content
GATEiit

GATE CSE · Algorithms

Graph traversals, minimum spanning trees and shortest paths

BFS and DFS with edge classification and topological sort, minimum spanning trees by Kruskal and Prim, and shortest paths by Dijkstra, Bellman–Ford and Floyd–Warshall, with the running times and hand traces GATE asks for.

Before you start

This topic comes before: Distance vector and link state routing, Transactions and concurrency control, Hierarchical clustering: top-down and bottom-up; single-linkage and multiple-linkage

Concept notes

1. BFS and DFS

Both visit every vertex and edge once: Θ(V+E) with adjacency lists, Θ(V2) with an adjacency matrix.

Breadth-first search (BFS) uses a queue and visits vertices in order of distance (number of edges) from the source. So BFS gives shortest paths in unweighted graphs. In an undirected graph, a non-tree edge joins vertices whose BFS levels differ by at most 1.

Depth-first search (DFS) uses a stack (or recursion). It gives each vertex a discovery time d[v] and finish time f[v]. The intervals [d,f] of any two vertices are either nested or disjoint (parenthesis theorem).

DFS edge types in a directed graph:

Edge (u,v) Meaning Times
Tree v first found from u d[u]<d[v]<f[v]<f[u]
Back v is an ancestor of u d[v]<d[u]<f[u]<f[v]
Forward v is a non-child descendant like tree
Cross neither d[v]<f[v]<d[u]<f[u]

In an undirected graph DFS finds only tree and back edges.

A graph has a cycle if and only if DFS finds a back edge. DFS also finds connected components, strongly connected components (two passes, Kosaraju), articulation points and bridges, all in Θ(V+E).

2. Topological sort

A topological order of a directed graph lists the vertices so that every edge u→v has u before v. It exists if and only if the graph is a DAG (no directed cycle).

Two Θ(V+E) methods:

  • DFS: output vertices in decreasing finish time.
  • Kahn's algorithm: repeatedly remove a vertex of in-degree 0. If vertices remain but none has in-degree 0, the graph has a cycle.

The order is unique if and only if consecutive vertices in it are joined by edges (a Hamiltonian path). Otherwise there are several; GATE often asks you to count them. Count by asking, at each step, which in-degree-0 vertices could come next, or by spotting independent groups and multiplying.

Uses: task scheduling with dependencies, and single-source shortest paths in a DAG in Θ(V+E) by relaxing edges in topological order (this works even with negative weights).

3. Minimum spanning trees

A spanning tree of a connected graph with V vertices has exactly V−1 edges. A minimum spanning tree (MST) has the least total weight.

  • Cut property: the lightest edge crossing any cut is in some MST (in every MST if it is the unique lightest).
  • Cycle property: the heaviest edge on a cycle, if unique, is in no MST.
  • If all edge weights are distinct, the MST is unique.
  • An MST also minimises the largest edge weight on the tree (it is a minimum bottleneck spanning tree).
Algorithm Idea Time
Kruskal sort edges; add the next lightest that joins two different components (union–find) O(Elog⁡E)=O(Elog⁡V)
Prim, binary heap grow one tree; add the lightest edge leaving it O(Elog⁡V)
Prim, array same, scanning an array for the minimum O(V2), good for dense graphs

Kruskal can hold a forest of several trees midway; Prim always holds one tree. Adding a constant to every weight does not change the MST, but it can change shortest paths.

ABCDE41258103
Weighted graph used in the examples; thick edges form the MST (weight 11)

4. Shortest paths

All shortest-path algorithms use relaxation: if d[u]+w(u,v)<d[v], set d[v]=d[u]+w(u,v) and π[v]=u.

Algorithm Problem Weights Time
BFS single source unweighted Θ(V+E)
DAG relaxation single source any, DAG only Θ(V+E)
Dijkstra single source non-negative O((V+E)log⁡V) heap; O(V2) array
Bellman–Ford single source any; detects negative cycles Θ(VE)
Floyd–Warshall all pairs any, no negative cycle Θ(V3)

Dijkstra repeatedly finalises the unvisited vertex with the smallest d. A negative edge can later lower an already final distance, so Dijkstra can give wrong answers with negative edges.

Bellman–Ford relaxes every edge V−1 times (a shortest path has at most V−1 edges). If a V-th round still lowers some d, a negative cycle is reachable from the source.

Floyd–Warshall allows intermediate vertices 1..k in round k: dk[i][j]=min⁡(dk−1[i][j], dk−1[i][k]+dk−1[k][j]). A negative d[i][i] at the end means a negative cycle through i.

Formulas to remember

BFS / DFS time
Θ(V+E) (lists),Θ(V2) (matrix)
Spanning tree size
∣ET∣=V−1
Kruskal
O(Elog⁡E)=O(Elog⁡V)
Prim / Dijkstra with binary heap
O((V+E)log⁡V)
Relaxation
d[v]←min⁡(d[v], d[u]+w(u,v))
Bellman–Ford
Θ(VE), V−1 rounds
Floyd–WarshallTotal Θ(V3)
dk[i][j]=min⁡(dk−1[i][j], dk−1[i][k]+dk−1[k][j])

Common mistakes

  • Running Dijkstra on a graph with negative edges; use Bellman–Ford or, for a DAG, topological-order relaxation.
  • Using BFS for shortest paths in a weighted graph; it counts edges, not weights.
  • In Kruskal, adding an edge whose endpoints are already in the same component.
  • Assuming the MST is unique when edge weights repeat.
  • Thinking that adding a constant to every edge keeps shortest paths the same; it keeps the MST, not shortest paths.
  • Quoting Θ(V+E) for BFS or DFS on an adjacency matrix; it is Θ(V2).

Worked examples

Try each step yourself, then reveal the working.

Example 1: Dijkstra by hand

numerical

In the undirected graph shown (edges A–B 4, A–C 1, B–C 2, B–D 5, C–D 8, C–E 10, D–E 3), find the shortest distance from A to every vertex using Dijkstra's algorithm.

  1. Step 1: Start at A and relax its edges.

    Try it on paper first.

Example 2: Kruskal by hand

numerical

Find the MST of the same graph using Kruskal's algorithm and give its weight.

  1. Step 1: Sort the edges by weight.

    Try it on paper first.

Example 3: Counting topological orders

numerical

A DAG has vertices a, b, c, d, e and edges a→c, b→c, c→d, c→e. How many topological orders does it have?

  1. Step 1: Which vertices must come before c, and which after?

    Try it on paper first.

Example 4: Why Dijkstra fails with a negative edge

conceptual

Directed edges: S→B weight 2, S→C weight 3, C→B weight −2. What does Dijkstra report for d[B], and what is the true distance?

  1. Step 1: Run Dijkstra from S.

    Try it on paper first.

Previous year questions

32 official GATE CSE questions on this topic, newest first.

Practise these 32 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE CSE syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.