Skip to content
GATEiit

GATE DA · Programming, Data Structures and Algorithms

Basic graph algorithms: traversals and shortest path

Breadth-first and depth-first search, their orders, trees, edge types and uses (levels, cycles, topological sort), and single-source shortest paths with Dijkstra and Bellman–Ford, with costs and tracing.

Before you start

  • Graph basics and representations →

    Traversal costs are stated in terms of n, m and the adjacency list or matrix.

  • Stacks and queues →

    BFS runs on a queue and DFS on a stack (or recursion).

  • Priority queue (binary heap)

    Dijkstra's running time depends on how the next closest vertex is extracted.

This topic comes before: Search: informed, uninformed and adversarial

Concept notes

1. Breadth-first search (BFS)

BFS explores a graph level by level from a source s, using a queue.

from collections import deque

def bfs(g, s):
    dist = {s: 0}
    q = deque([s])
    while q:
        u = q.popleft()
        for v in g[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                q.append(v)
    return dist
  • A vertex is marked when it is added to the queue, so it is enqueued only once.
  • dist[v] is the fewest edges from s to v. So BFS finds shortest paths in an unweighted graph.
  • The edges used to discover vertices form a BFS tree. In an undirected graph, every non-tree edge joins vertices whose levels differ by at most 1.
  • Cost: Θ(n+m) with adjacency lists, Θ(n2) with a matrix.

Uses: shortest paths by edge count, connected components (run BFS from each unvisited vertex), and bipartite testing: colour levels alternately; the graph is bipartite if no edge joins two vertices of the same level.

The visiting order depends on the order of neighbours in each list. GATE questions usually say "in alphabetical order" or give the lists; when several orders are possible, check each option against the rule that a vertex's neighbours are enqueued together, before any later vertex's neighbours.

2. Depth-first search (DFS)

DFS goes as deep as possible along one path before backing up. It uses recursion (or an explicit stack). Each vertex gets a discovery time d[v] and a finish time f[v].

def dfs(g, u, seen, order):
    seen.add(u)
    for v in g[u]:
        if v not in seen:
            dfs(g, v, seen, order)
    order.append(u)   # u finishes here

Parenthesis property: the intervals [d,f] of two vertices are either disjoint or one contains the other; v is a descendant of u exactly when d[u]<d[v]<f[v]<f[u].

Edge types in a directed graph:

Edge (u,v) Meaning
Tree v first discovered from u
Back v is an ancestor of u
Forward v is a non-child descendant of u
Cross all others (v already finished, not related)

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

Uses:

  • A directed graph has a cycle if and only if DFS finds a back edge.
  • Topological sort of a DAG: list vertices in decreasing finish time.
  • Connected components, and (with more work) strongly connected components, bridges and cut vertices.

Cost: Θ(n+m) with adjacency lists.

3. Dijkstra's algorithm

Dijkstra finds shortest distances from s in a graph with non-negative edge weights.

  1. Set d[s]=0 and d[v]=∞ for all others.
  2. Repeatedly take the unfinished vertex u with the smallest d[u] and mark it finished.
  3. Relax each edge (u,v) of weight w: if d[u]+w<d[v], set d[v]=d[u]+w and record u as v's parent.

Once a vertex is finished its distance never changes. This greedy step is correct only because no edge is negative.

Running time:

Priority queue Time
Unsorted array O(n2) (good for dense graphs)
Binary heap O((n+m)log⁡n)
Fibonacci heap O(m+nlog⁡n)

With a negative edge, Dijkstra can finish a vertex too early and give a wrong answer, even when there is no negative cycle.

The parent pointers form a shortest-path tree. Shortest paths are not always unique; when the question asks for the order in which vertices are finished, break ties as the question states.

If every edge has the same weight, Dijkstra reduces to BFS.

4121538SABCDShortest distances from S: S 0, B 1, A 3, C 4, D 7
A weighted directed graph: Dijkstra finishes S, B, A, C, D in that order

4. Bellman–Ford, DAGs and all pairs

Bellman–Ford handles negative edge weights. It relaxes every edge, n−1 times over. After round k, d[v] is at most the shortest distance using at most k edges; a shortest simple path has at most n−1 edges, so n−1 rounds suffice.

  • Time: O(nm).
  • Negative cycle test: run one more round. If any distance still decreases, a negative cycle is reachable from s and shortest paths are undefined.
  • It may finish early if a round changes nothing.

Shortest paths in a DAG: process vertices in topological order and relax their outgoing edges. This is O(n+m) and works with negative edges, since a DAG has no cycles at all.

All pairs: Floyd–Warshall computes every pair in O(n3) using dij←min⁡(dij, dik+dkj) for each intermediate k. It allows negative edges but not negative cycles.

Problem Algorithm Time
Unweighted, single source BFS O(n+m)
Non-negative weights Dijkstra (heap) O((n+m)log⁡n)
Negative weights allowed Bellman–Ford O(nm)
DAG, any weights Topological order O(n+m)
All pairs Floyd–Warshall O(n3)

Adding the same constant to every edge does not preserve shortest paths, because paths with more edges gain more; multiplying every weight by a positive constant does.

Formulas to remember

Relaxation
d[v]←min⁡(d[v],  d[u]+w(u,v))
BFS / DFS time (adjacency lists)
Θ(n+m)
Dijkstra with a binary heap
O((n+m)log⁡n)
Bellman–Fordn−1 rounds of relaxing all m edges
O(nm)
Floyd–Warshall update
dij←min⁡(dij,  dik+dkj)

Common mistakes

  • Using Dijkstra on a graph with negative edges; use Bellman–Ford, or the DAG method when there is no cycle.
  • Marking a BFS vertex as visited when it is dequeued instead of enqueued, which can add it twice.
  • Taking topological order as increasing finish time; it is decreasing finish time.
  • Assuming DFS finds shortest paths in an unweighted graph; only BFS does.
  • Adding a constant to all weights to remove negative edges; this changes which path is shortest.

Worked examples

Try each step yourself, then reveal the working.

Example 1: BFS order and levels

numerical

An undirected graph has edges 1–2, 1–3, 2–4, 2–5, 3–5, 3–6, 5–7, 6–7. Run BFS from 1, taking neighbours in increasing order. Give the visiting order and the distance of each vertex.

  1. Step 1: Dequeue 1 and enqueue its neighbours.

    Try it on paper first.

Example 2: DFS times and topological order

numerical

A DAG has edges a→b, a→c, b→d, c→d, c→f, d→e. Run DFS from a, visiting neighbours alphabetically and starting new trees alphabetically. Give the discovery and finish times and a topological order.

  1. Step 1: Go deep from a.

    Try it on paper first.

Example 3: Tracing Dijkstra

numerical

Run Dijkstra from S on the graph in the figure: S→A 4, S→B 1, B→A 2, A→C 1, B→C 5, B→D 8, C→D 3.

  1. Step 1: Finish S and relax its edges.

    Try it on paper first.

Example 4: Why Dijkstra fails with a negative edge

conceptual

Edges: S→A 4, S→B 6, B→A −3, A→T 2, B→T 4. Compare Dijkstra's answer for T with the true shortest distance.

  1. Step 1: Run Dijkstra.

    Try it on paper first.

Previous year questions

5 official GATE DA questions on this topic, newest first.

Practise these 5 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 DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.