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.
BFS explores a graph level by level from a source , 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 to . 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: with adjacency lists, 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 and a finish time .
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 of two vertices are either disjoint or one contains the other; is a descendant of exactly when .
Edge types in a directed graph:
Edge
Meaning
Tree
first discovered from
Back
is an ancestor of
Forward
is a non-child descendant of
Cross
all others ( 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: with adjacency lists.
3. Dijkstra's algorithm
Dijkstra finds shortest distances from in a graph with non-negative edge weights.
Set and for all others.
Repeatedly take the unfinished vertex with the smallest and mark it finished.
Relax each edge of weight : if , set and record as '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
(good for dense graphs)
Binary heap
Fibonacci heap
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.
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, times over. After round , is at most the shortest distance using at most edges; a shortest simple path has at most edges, so rounds suffice.
Time: .
Negative cycle test: run one more round. If any distance still decreases, a negative cycle is reachable from 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 and works with negative edges, since a DAG has no cycles at all.
All pairs:Floyd–Warshall computes every pair in using for each intermediate . It allows negative edges but not negative cycles.
Problem
Algorithm
Time
Unweighted, single source
BFS
Non-negative weights
Dijkstra (heap)
Negative weights allowed
Bellman–Ford
DAG, any weights
Topological order
All pairs
Floyd–Warshall
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
BFS / DFS time (adjacency lists)
Dijkstra with a binary heap
Bellman–Ford rounds of relaxing all edges
Floyd–Warshall update
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.
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.
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.
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.
Step 1: Run Dijkstra.
Try it on paper first.
Previous year questions
5 official GATE DA questions on this topic, newest first.
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.