IAE Academy

GATE CS · DA

Graphs

Traversals, minimum spanning trees and shortest paths

Graph traversal (BFS, DFS with timestamps and edge classification), ordering and connectivity (topological sort, connected and strongly connected components), minimum spanning trees (Kruskal, Prim, cut and cycle properties) and shortest paths (BFS, DAG relaxation, Dijkstra, Bellman-Ford, Floyd-Warshall): the exact procedures, the conditions under which each algorithm is correct, and their time and space costs, with hand-traced worked examples and original practice problems.

28 previous-year questions · 27 solved · 5 practice questions

Graph Representations and Traversal Basics (BFS)

A graph models pairwise relationships between a set of vertices and a set of edges . Two representations recur throughout: the adjacency matrix, a 0/1 (or weight) matrix, and the adjacency list, an array of lists where list holds every vertex adjacent to .

Conventions used throughout these notes (assume them unless a question says otherwise): and also denote the number of vertices and edges; graphs are simple (no self-loops or parallel edges); an undirected edge is stored in both endpoints' adjacency lists; complexities are worst case and assume adjacency lists unless stated; logarithms are base 2 (the base does not change an -bound); for unweighted graphs, distance means number of edges.

SPACE COST OF THE TWO REPRESENTATIONS

Use the matrix when the graph is dense (E close to V^2) or constant-time edge checks are needed; use the list when the graph is sparse (E much smaller than V^2). An undirected graph's adjacency lists hold 2E entries in total (each edge appears in both endpoints' lists); a directed graph's hold E.

HANDSHAKE LEMMA AND EDGE BOUNDS (SIMPLE GRAPHS)

The degree sum counts every undirected edge once from each end. Consequence: every undirected graph has an even number of odd-degree vertices. In a directed graph, the sum of in-degrees = the sum of out-degrees = E.

Operation

Adjacency Matrix

Adjacency List

Space

O(V^2)

O(V+E)

Check if edge (u,v) exists

O(1)

O(deg(u)), worst case O(V)

Iterate over all neighbours of u

O(V)

O(deg(u))

Add an edge (no duplicate check)

O(1)

O(1) (prepend to the list)

Visit every vertex and edge (BFS/DFS over the whole graph)

O(V^2)

O(V+E)

BFS procedure (single source s)

  1. Mark s visited, set dist[s] = 0, and enqueue s.

  2. While the queue is non-empty, dequeue a vertex u.

  3. For every unvisited neighbour v of u: mark v visited, set dist[v] = dist[u] + 1 and parent[v] = u, then enqueue v.

  4. When the queue empties, every vertex reachable from s has been visited exactly once, and dist[] holds the shortest-path length (number of edges) from s. This is correct only for UNWEIGHTED graphs (or all weights equal); weighted graphs need Dijkstra, Bellman-Ford or DAG relaxation.

  5. Running time: O(V+E) with adjacency lists, O(V^2) with an adjacency matrix.

WORKED EXAMPLE

Run BFS from vertex 1 on the undirected graph with adjacency lists 1:{2,3}, 2:{1,4}, 3:{1,4}, 4:{2,3,5}, 5:{4}, visiting the smaller-labelled neighbour first. Give the BFS levels and the order in which vertices are dequeued.

Solution
  1. Level 0 = {1}; enqueue 1.

  2. Dequeue 1: neighbours 2 and 3 are unvisited, so they are level 1; enqueue 2 then 3.

  3. Dequeue 2: neighbour 1 is already visited; neighbour 4 is unvisited, so it is level 2; enqueue 4.

  4. Dequeue 3: neighbours 1 and 4 are both already visited, so nothing new is added.

  5. Dequeue 4: neighbours 2 and 3 are already visited; neighbour 5 is unvisited, so it is level 3; enqueue 5.

  6. Dequeue 5: neighbour 4 is already visited. The queue is now empty and BFS terminates.

Answer: Levels: {1}, {2,3}, {4}, {5}. Dequeue order: 1, 2, 3, 4, 5.

A short C implementation of BFS, with each vertex's neighbours kept in a row of a 2-D array and a plain array as the queue:

#define MAXV 100
int adj[MAXV][MAXV];   /* adj[u][0] = degree of u, adj[u][1..deg] = its neighbours */
int dist[MAXV], visited[MAXV];

void bfs(int s, int V) {
    int queue[MAXV], front = 0, rear = 0;
    for (int i = 0; i < V; i++) {
        visited[i] = 0;
        dist[i] = -1;
    }
    visited[s] = 1;
    dist[s] = 0;
    queue[rear++] = s;
    while (front < rear) {
        int u = queue[front++];
        int deg = adj[u][0];
        for (int i = 1; i <= deg; i++) {
            int v = adj[u][i];
            if (!visited[v]) {
                visited[v] = 1;
                dist[v] = dist[u] + 1;
                queue[rear++] = v;
            }
        }
    }
}

The code numbers vertices 0 to V-1. To run it on the worked example (vertices 1 to 5), store each row's neighbours in increasing order and call bfs(1, 6). Slot 0 is never reached, so dist[0] stays −1. The dequeue order is 1, 2, 3, 4, 5, and dist[1] to dist[5] are 0, 1, 1, 2, 3. Each vertex enters the queue at most once, so a queue of MAXV slots never overflows. The running time is O(V+E) because only the deg(u) filled slots of each row are scanned, although the array itself reserves MAXV × MAXV ints.

Facts about BFS

  1. In an undirected graph, every edge not in the BFS tree joins two vertices whose levels differ by at most 1.

  2. In a directed graph, every edge (u,v) between visited vertices satisfies level(v) ≤ level(u) + 1 (it may go back up any number of levels, but never skips a level going down).

  3. A graph is bipartite if and only if it has no odd-length cycle. BFS tests this for each component: colour vertices by the parity of their level; the graph is bipartite iff no edge joins two vertices of the same level.

  4. BFS from s visits exactly the vertices reachable from s. Restarting it from each still-unvisited vertex counts the connected components of an undirected graph in O(V+E) total.

EXAM TIP

A BFS or DFS order is not unique in general: it depends on the order in which neighbours are stored and visited. A question either fixes that order (as the example above does) or asks only about something order-independent, such as the BFS level of each vertex or the set of connected components. Do not assume a unique traversal order unless the question pins it down.

DFS, Discovery/Finish Times and Edge Classification

Depth-first search explores as far as possible along a branch before backtracking. Each vertex gets a discovery time (when it is first visited) and a finish time (when its recursive call returns, after all its descendants are done). DFS runs in time with adjacency lists and with an adjacency matrix. The timestamps classify every edge and underlie topological sort and the strongly-connected-component algorithm in the next section.

DFS-VISIT procedure (with timestamps)

  1. Initialise a global counter time = 0 and color[v] = WHITE for every vertex.

  2. DFS-VISIT(u): set color[u] = GRAY, increment time, set d[u] = time.

  3. For every neighbour v of u (in adjacency-list order): if color[v] == WHITE, set parent[v] = u and recursively call DFS-VISIT(v).

  4. After all neighbours of u are processed, set color[u] = BLACK, increment time, set f[u] = time.

  5. The outer DFS loop calls DFS-VISIT on every still-WHITE vertex in vertex-id order. This produces a DFS forest (several trees) if not every vertex is reachable from the first one.

Edge (u,v) type

Definition

Detected as (directed graph)

Occurs in an undirected graph's DFS?

Tree edge

v is discovered from u

color[v] = WHITE when explored

Yes

Back edge

v is an ancestor of u in the DFS forest (a self-loop also counts)

color[v] = GRAY when explored

Yes

Forward edge

v is a proper descendant of u, and the edge is not a tree edge

color[v] = BLACK and d[u] < d[v]

No

Cross edge

v is neither an ancestor nor a descendant of u

color[v] = BLACK and d[u] > d[v]

No

PARENTHESIS THEOREM (FOR TWO VERTICES WITH D[U] < D[V])

Exactly one of the two holds. The first means v is a descendant of u in the DFS forest (the intervals are nested). The second means neither is a descendant of the other (the intervals are disjoint). Partial overlap, d[u] < d[v] < f[u] < f[v], is impossible.

White-path theorem. In a DFS forest, is a descendant of if and only if, at time , there is a path from to made up entirely of WHITE vertices.

Finish times along edges (directed graph). For a tree, forward or cross edge , . For a back edge, . So in a DAG, which has no back edges, every edge goes from a larger finish time to a smaller one. This is why DFS-based topological sort works.

Cycle test. A directed graph has a cycle if and only if DFS finds a back edge. An undirected graph has a cycle if and only if DFS meets an already-visited vertex other than the current vertex's parent.

WORKED EXAMPLE

Run DFS from vertex 1 on the directed graph with edges 1→2, 2→3, 3→1, 1→4, visiting neighbours in increasing label order. Give the discovery and finish times of all vertices and classify every edge.

Solution
  1. Start DFS-VISIT(1): d[1] = 1, color[1] = GRAY.

  2. The neighbours of 1 in order are 2, then 4. Visit 2 first: color[2] = WHITE, so (1,2) is a tree edge; d[2] = 2.

  3. The only neighbour of 2 is 3. color[3] = WHITE, so (2,3) is a tree edge; d[3] = 3.

  4. The only neighbour of 3 is 1. color[1] = GRAY (1 is an ancestor still on the recursion stack), so (3,1) is a back edge.

  5. 3 has no more neighbours: color[3] = BLACK, f[3] = 4.

  6. Back in 2, with no more neighbours: color[2] = BLACK, f[2] = 5.

  7. Back in 1, the next neighbour is 4. color[4] = WHITE, so (1,4) is a tree edge; d[4] = 6. 4 has no neighbours: color[4] = BLACK, f[4] = 7.

  8. 1 has no more neighbours: color[1] = BLACK, f[1] = 8.

Answer: Times: d[1]=1, f[1]=8; d[2]=2, f[2]=5; d[3]=3, f[3]=4; d[4]=6, f[4]=7. Edges: (1,2) tree, (2,3) tree, (3,1) back, (1,4) tree. The back edge (3,1) shows that the graph has the cycle 1→2→3→1.

A DFS that classifies the edges of a directed graph (vertices 0 to V-1, using the adj layout from the BFS code):

int color[MAXV];   /* 0 = WHITE, 1 = GRAY, 2 = BLACK */
int disc[MAXV], fin[MAXV], timer = 0;

void dfsVisit(int u) {
    color[u] = 1;
    disc[u] = ++timer;
    int deg = adj[u][0];
    for (int i = 1; i <= deg; i++) {
        int v = adj[u][i];
        if (color[v] == 0) {
            dfsVisit(v);                 /* tree edge */
        } else if (color[v] == 1) {
            /* back edge: v is an ancestor of u */
        } else if (disc[u] < disc[v]) {
            /* forward edge */
        } else {
            /* cross edge */
        }
    }
    color[u] = 2;
    fin[u] = ++timer;
}

EXAM TIP

In an undirected graph each edge sits in both endpoints' lists, so DFS meets it twice. Classify it the first time it is met: an edge to a WHITE vertex is a tree edge, and an edge from u to a GRAY vertex other than parent[u] is a back edge. Ignore the second sighting, whether that is u seeing its parent over the tree edge or an ancestor seeing an already-BLACK descendant over a back edge. Under this convention only tree and back edges occur; forward and cross edges are impossible. The directed-graph code above, run unchanged on an undirected graph, would wrongly report each parent edge as a back edge and each back edge's second sighting as a forward edge.

Topological Sort, Connected Components and Strongly Connected Components

A topological order of a directed graph is a linear ordering of its vertices such that for every directed edge , appears before . One exists if and only if the graph is a directed acyclic graph (DAG); any directed cycle makes it impossible. An undirected graph splits into connected components, found by one BFS/DFS started from each still-unvisited vertex. A directed graph splits into strongly connected components (SCCs): maximal sets of vertices in which every vertex has a directed path to every other.

Kahn's algorithm (BFS-based topological sort)

  1. Compute the in-degree of every vertex.

  2. Enqueue all vertices whose in-degree is 0.

  3. Repeatedly dequeue a vertex u, append it to the output, and decrement the in-degree of every out-neighbour v of u. Enqueue v the moment its in-degree becomes 0.

  4. If fewer than V vertices have been output when the queue empties, the graph contains a cycle and no topological order exists.

DFS-based topological sort

  1. Run DFS over the whole graph (a DFS forest if needed), starting from every unvisited vertex.

  2. Whenever a vertex finishes (turns BLACK), push it onto a stack.

  3. Popping the stack from top to bottom, which is decreasing order of finish time, gives a valid topological order.

  4. This works only on a DAG. A back edge found during the DFS proves that a cycle exists, so no topological order can be produced.

Kosaraju's algorithm for SCCs

  1. Run DFS on G and push each vertex onto a stack the moment it finishes, exactly as in DFS-based topological sort.

  2. Build : the same graph with every edge reversed.

  3. Pop vertices off the stack one at a time. For each popped vertex still unvisited in , run a DFS from it in . The vertices reached by that single DFS form one complete SCC.

  4. Continue until the stack is empty. The number of DFS calls started in step 3 equals the number of SCCs.

Algorithm

Time

Extra space

Kahn's topological sort

O(V+E)

O(V)

DFS-based topological sort

O(V+E)

O(V)

Connected components (undirected, BFS/DFS)

O(V+E)

O(V)

Kosaraju's SCC algorithm

O(V+E)

O(V+E) (it builds the reversed graph)

EXAM TIP

A DAG can have several topological orders. It has exactly one if and only if it contains a directed path through all of its vertices; equivalently, the queue in Kahn's algorithm never holds more than one vertex at a time. Every DAG has at least one vertex of in-degree 0 and at least one of out-degree 0. A directed graph is strongly connected if and only if it has exactly one SCC. Contracting each SCC to a single vertex (the condensation) always gives a DAG, whatever the original graph.

Minimum Spanning Trees: Kruskal, Prim, Cut and Cycle Properties

A minimum spanning tree (MST) of a connected, undirected, edge-weighted graph is a spanning tree whose total edge weight is the smallest among all spanning trees. Weights may be negative: Kruskal and Prim only ever compare weights. Repeated weights are allowed, and they are what make an MST possibly non-unique.

Cut property and cycle property

  1. Cut property: for any cut (a partition of V into two non-empty sets), if one edge crossing the cut is strictly lighter than every other crossing edge, it belongs to EVERY MST. If several crossing edges tie for the minimum weight, every MST contains at least one of them.

  2. Cycle property: for any cycle, if one edge on it is strictly heavier than every other edge on the cycle, it belongs to NO MST. If several edges tie for the maximum on a cycle, each of them can belong to some MST, but never to every MST.

  3. These two properties are what make the greedy choices of Kruskal and Prim always safe.

Kruskal's algorithm

  1. Sort all E edges by weight, ascending.

  2. Initialise a Disjoint Set Union (Union-Find) structure with every vertex in its own singleton set.

  3. Process the edges (u,v) in sorted order. If Find(u) ≠ Find(v), add (u,v) to the MST and Union(u,v). Otherwise discard the edge, because adding it would close a cycle.

  4. Stop as soon as V−1 edges have been added.

Prim's algorithm

  1. Pick any start vertex r; set key[r] = 0 and key[v] = infinity for every other vertex.

  2. Keep a priority queue of the vertices outside the tree, keyed by the lightest edge known so far from each vertex to the tree.

  3. Repeatedly extract the vertex u with the smallest key and add u to the tree, together with its edge (parent[u], u) unless u = r.

  4. For every neighbour v of u still outside the tree: if weight(u,v) < key[v], set key[v] = weight(u,v) and parent[v] = u.

  5. Repeat until all V vertices are in the tree.

NUMBER OF EDGES IN A SPANNING TREE OR FOREST

The first holds for any spanning tree of a connected graph on V vertices, whatever the weights. The second is for a graph with k connected components, where Kruskal run to completion produces a minimum spanning forest.

NUMBER OF LABELLED SPANNING TREES OF THE COMPLETE GRAPH K_N

For example, K_4 has 4^2 = 16 spanning trees. This counts spanning trees, not MSTs; with distinct weights, exactly one of them is the MST.

Algorithm

Data structure

Time complexity

Kruskal

Sort the edges + Union-Find (union by rank, path compression)

O(E log E) = O(E log V), since E ≤ V^2 gives log E ≤ 2 log V; sorting dominates

Prim

Binary heap + adjacency list

O((V+E) log V), which is O(E log V) for a connected graph

Prim

Plain array scan for the minimum key + adjacency matrix

O(V^2), better than the heap version on a dense graph

Prim

Fibonacci heap + adjacency list

O(E + V log V)

WORKED EXAMPLE

For the graph on vertices {1,...,5} with weighted edges (1,2)=4, (1,3)=2, (2,3)=1, (2,4)=5, (3,4)=8, (3,5)=3, (4,5)=7, find the total weight of the minimum spanning tree using Kruskal's algorithm.

Solution
  1. Sort the edges ascending: (2,3)=1, (1,3)=2, (3,5)=3, (1,2)=4, (2,4)=5, (4,5)=7, (3,4)=8.

  2. Add (2,3)=1: this forms the set {2,3}; {1}, {4} and {5} are still separate.

  3. Add (1,3)=2: 1 and 3 are in different sets, so merge them into {1,2,3}.

  4. Add (3,5)=3: 3 and 5 are in different sets, so merge them into {1,2,3,5}.

  5. (1,2)=4: 1 and 2 are already in the same set, so this edge would form a cycle; discard it.

  6. Add (2,4)=5: 2 and 4 are in different sets, so merge them into {1,2,3,4,5}. Now V−1 = 4 edges have been added, so stop.

Answer: MST edges: (2,3), (1,3), (3,5), (2,4). Total weight = 1 + 2 + 3 + 5 = 11.

Further MST facts

  1. All MSTs of a graph have the same total weight and, more strongly, the same sorted list of edge weights.

  2. Adding a constant to every edge weight, or applying any strictly increasing function to the weights, leaves the set of MSTs unchanged, because only the order of the weights matters. Shortest paths do NOT behave this way (see the next section).

  3. An MST also minimises the heaviest edge among all spanning trees: it is a minimum bottleneck spanning tree. The converse need not hold.

  4. Kruskal and Prim remain correct with negative edge weights.

EXAM TIP

Uniqueness: if all edge weights are pairwise distinct, the MST is unique. This condition is sufficient but not necessary; a graph with repeated weights can still have a unique MST. When a weight repeats, check whether the tied edges are actually interchangeable, i.e. whether they tie for the minimum across some cut or for the maximum on some cycle, before answering whether the MST is unique.

Single-Source Shortest Paths: DAG Relaxation, Dijkstra and Bellman-Ford

Single-source shortest-path algorithms compute, from one source vertex , the minimum total weight of a path to every other vertex. For unweighted graphs, BFS already does this in . The algorithms below handle weighted directed graphs; an undirected edge can be treated as two opposite directed edges of the same weight. Convention: assume all edge weights are non-negative unless a question explicitly allows negative ones.

Shortest paths in a DAG

  1. Topologically sort the DAG.

  2. Set dist[s] = 0 and dist[v] = infinity for every other vertex.

  3. Take the vertices u in topological order and relax every edge (u,v) leaving u: if dist[u] + w(u,v) < dist[v], set dist[v] = dist[u] + w(u,v).

  4. Time O(V+E). This is correct even with negative edge weights, because a DAG has no cycles at all.

Dijkstra's algorithm

  1. Set dist[s] = 0 and dist[v] = infinity for every other vertex; no vertex is finalised yet.

  2. Repeatedly extract the non-finalised vertex u with the smallest dist[u]. This greedy choice is the crux of the algorithm.

  3. Mark u as finalised. If every edge weight is non-negative, dist[u] is now correct and never changes again.

  4. Relax every edge (u,v) from u to a vertex v that is not yet finalised: if dist[u] + w(u,v) < dist[v], set dist[v] = dist[u] + w(u,v) and parent[v] = u.

  5. Repeat until every vertex is finalised, or stop once a required target vertex has been extracted.

DIJKSTRA'S TIME COMPLEXITY

Correctness is guaranteed only when all edge weights are non-negative. The array version suits dense graphs (E close to V^2); the binary-heap version suits sparse graphs (E much smaller than V^2).

Bellman-Ford algorithm

  1. Set dist[s] = 0 and dist[v] = infinity for every other vertex.

  2. Repeat V−1 times: relax every edge (u,v) of the graph (in any fixed order), setting dist[v] = dist[u] + w(u,v) whenever that is smaller.

  3. Why V−1 rounds suffice: if no negative cycle is reachable from s, every shortest path can be taken to be simple, so it has at most V−1 edges. After round i, every vertex whose shortest path uses at most i edges has its correct distance.

  4. You can stop early if a whole round changes nothing, since the distances are already final.

  5. Run one extra (V-th) round. If any edge can still be relaxed, a negative-weight cycle is reachable from s, and the distance to every vertex reachable from that cycle is undefined (−∞).

BELLMAN-FORD'S TIME COMPLEXITY

Each of the V−1 rounds scans all E edges once; the extra negative-cycle check costs another O(E).

Situation

Dijkstra

Bellman-Ford

All edge weights ≥ 0

Correct, faster

Correct, slower

Some negative edge, no negative cycle

Not guaranteed; can report a distance that is too large

Correct

Negative-weight cycle reachable from s

Output meaningless

Detects and reports the cycle

Time complexity

O((V+E) log V) with a binary heap

O(VE)

WORKED EXAMPLE

Consider the directed graph with edges A→B (weight 1), A→C (weight 2), C→B (weight −5) and B→D (weight 2). It has no cycle at all. Run Dijkstra's algorithm, as stated above, from source A and compare its output with the true distances.

Solution
  1. Initialise dist[A] = 0 and dist[B] = dist[C] = dist[D] = infinity.

  2. Extract A (0) and finalise it. Relax A→B: dist[B] = 1. Relax A→C: dist[C] = 2.

  3. The non-finalised vertices are B (1), C (2) and D (infinity). Extract B (1) and finalise it. Relax B→D: dist[D] = 1 + 2 = 3.

  4. Extract C (2) and finalise it. The edge C→B would give 2 + (−5) = −3 < 1, but B is already finalised, so it is not relaxed.

  5. Extract D (3) and finalise it. D has no outgoing edges. The algorithm terminates.

Answer: Dijkstra reports dist[B] = 1 and dist[D] = 3. The true distances are dist[B] = −3 (A→C→B: 2 + (−5)) and dist[D] = −1 (A→C→B→D: 2 − 5 + 2). An implementation that does lower dist[B] to −3 when it processes C still reports dist[D] = 3, because B has already left the queue and its edge B→D is never relaxed again. Bellman-Ford, or DAG relaxation since this graph is a DAG, returns the correct −3 and −1.

Bellman-Ford in C (vertices 0 to V-1, edges stored as three parallel arrays):

#define MAXE 1000
#define INF 1000000000
int dist[MAXV];
int edgeU[MAXE], edgeV[MAXE], edgeW[MAXE];
int V, E;

int bellmanFord(int s) {
    for (int i = 0; i < V; i++)
        dist[i] = INF;
    dist[s] = 0;
    for (int round = 1; round <= V - 1; round++) {
        for (int e = 0; e < E; e++) {
            int u = edgeU[e], v = edgeV[e], w = edgeW[e];
            if (dist[u] != INF && dist[u] + w < dist[v])
                dist[v] = dist[u] + w;
        }
    }
    /* one extra round to detect a negative cycle reachable from s */
    for (int e = 0; e < E; e++) {
        int u = edgeU[e], v = edgeV[e], w = edgeW[e];
        if (dist[u] != INF && dist[u] + w < dist[v])
            return 0;   /* negative-weight cycle detected */
    }
    return 1;           /* dist[] is correct and final */
}

Further shortest-path facts

  1. Optimal substructure: every subpath of a shortest path is itself a shortest path between its own endpoints.

  2. Multiplying every edge weight by the same positive constant does not change which paths are shortest. Adding the same constant c to every weight CAN change them, because a path with k edges grows by k·c, which penalises paths with more edges.

  3. In an undirected graph, a negative edge (u,v) is by itself a negative cycle u→v→u once it is treated as two directed edges, so shortest paths are undefined there.

  4. Distances computed by Dijkstra or Bellman-Ford are always lengths of real paths, so an unfinished or incorrect run can only over-estimate a distance, never under-estimate it (assuming no negative cycle).

EXAM TIP

'Dijkstra works as long as there is only one negative edge' is FALSE, as the worked example shows: one negative edge is enough to break it. Dijkstra's correctness is guaranteed only when every edge weight is non-negative. If any edge is negative, use Bellman-Ford for a single source, DAG relaxation if the graph is acyclic, or Floyd-Warshall for all pairs.

All-Pairs Shortest Paths: Floyd-Warshall and Full Summary

Floyd-Warshall solves the all-pairs shortest-path problem, the shortest distance between every ordered pair of vertices. It allows paths to use a growing set of permitted intermediate vertices, adding one vertex at a time. Vertices are numbered to in the recurrence.

FLOYD-WARSHALL RECURRENCE

d_k[i][j] is the length of the shortest path from i to j whose intermediate vertices all lie in {1,...,k}. d_0 is the input: d_0[i][i] = 0, d_0[i][j] = w(i,j) where a direct edge exists, and infinity otherwise. The answer is d_V.

Procedure

  1. Initialise dist[i][j] = w(i,j) if a direct edge exists, 0 if i = j, and infinity otherwise.

  2. For k = 1 to V: for i = 1 to V: for j = 1 to V: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]).

  3. A single matrix can be updated in place. During round k, dist[i][k] and dist[k][j] do not change when there is no negative cycle, because routing a path to or from k through k itself gains nothing.

  4. After the loops, dist[i][j] is the shortest-path length from i to j for every ordered pair, provided there is no negative-weight cycle.

  5. A negative-weight cycle exists if and only if, after the loops, some dist[i][i] < 0.

FLOYD-WARSHALL COMPLEXITY

Three nested loops over all V vertices. It is correct with negative edge weights as long as there is no negative-weight cycle, and it detects one if present. Replacing min with OR and + with AND gives the transitive-closure (reachability) algorithm, also O(V^3).

#define INF 1000000000
int dist[MAXV][MAXV];   /* pre-filled: dist[i][i] = 0, dist[i][j] = w(i,j) or INF */

void floydWarshall(int V) {
    for (int k = 0; k < V; k++)
        for (int i = 0; i < V; i++)
            for (int j = 0; j < V; j++)
                if (dist[i][k] != INF && dist[k][j] != INF &&
                    dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
    /* a negative cycle exists iff some dist[i][i] < 0 after this */
}

Master complexity summary

Problem

Algorithm

Time

Negative edge weights allowed?

Single-source shortest paths, unweighted

BFS

O(V+E)

Not applicable (no weights)

Single-source shortest paths in a DAG

Relax edges in topological order

O(V+E)

Yes (a DAG has no cycles)

Single-source shortest paths, weights ≥ 0

Dijkstra

O((V+E) log V) binary heap; O(V^2) array

No

Single-source shortest paths, general weights

Bellman-Ford

O(VE)

Yes; detects a negative cycle reachable from s

All-pairs shortest paths

Floyd-Warshall

O(V^3)

Yes, with no negative cycle; detects one

Minimum spanning tree

Kruskal

O(E log V)

Yes

Minimum spanning tree

Prim

O((V+E) log V) binary heap; O(V^2) array

Yes

Traversal, topological sort, connected components, SCCs

BFS / DFS / Kahn / Kosaraju

O(V+E)

Not applicable (weights unused)

EXAM TIP

In Floyd-Warshall the k-loop MUST be outermost. With k outermost, when round k begins, every dist[i][k] and dist[k][j] already holds the shortest length using intermediates from {1,...,k−1}. So every dist[i][j] correctly considers a detour through k. If the i-loop or j-loop is outermost instead, some dist[i][j] entries are finished before the entries they depend on are correct, and the result can be wrong.

PREVIOUS-YEAR QUESTIONS

28 questions from the CS and DA papers

Try each question first, then open the answer. One shows the official answer only. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE CSE 2026 Set 1 · GATE CSE 2026 Set 2 · GATE CSE 2025 Set 1 · GATE CSE 2025 Set 2 · GATE CSE 2024 Set 1 · GATE CSE 2024 Set 2 · GATE CSE 2023 · GATE CSE 2022 · GATE CSE 2020 · GATE CSE 2018 · GATE DA 2026 · GATE DA 2025 · GATE DA 2024

GATE 2026 CS1 Q.41

GATE 2026 · CS1Q.41 · 2 marks · MCQ

Let be an undirected, edge-weighted graph with integer weights. The weight of a path is the sum of the weights of the edges in that path. The length of a path is the number of edges in that path.

Let be a vertex in . For every and for every , let denote the weight of a shortest path (in terms of weight) from to of length at most . If there is no path from to of length at most , then .

Consider the statements:

S1: For every and , .

S2: For every , if is part of a shortest path (in terms of weight) from to , then for every , .

Which one of the following options is correct?

  1. (A)

    Only S1 is true

  2. (B)

    Only S2 is true

  3. (C)

    Both S1 and S2 are true

  4. (D)

    Neither S1 nor S2 is true

Answer and solution
See the question in the paper
GATE 2026 CS1 Q.41: answer and solution

GATE 2026 CS1 Q.49

GATE 2026 · CS1Q.49 · 2 marks · MSQ

Let be a simple, undirected, edge-weighted graph with unique edge weights.

Which of the following statements about the minimum spanning trees (MST) of is/are true?

  1. (A)

    In every cycle of , the edge with the largest weight in is not in any MST

  2. (B)

    In every cycle of , the edge with the smallest weight in is in every MST

  3. (C)

    For every vertex , the edge with the largest weight incident on is not in any MST

  4. (D)

    For every vertex , the edge with the smallest weight incident on is in every MST

Answer and solution
See the question in the paper
GATE 2026 CS1 Q.49: answer and solution

GATE 2026 CS1 Q.50

GATE 2026 · CS1Q.50 · 2 marks · MSQ

Consider the following pseudocode for depth-first search (DFS) algorithm which takes a directed graph as input, where and are the discovery time and finishing time, respectively, of the vertex .

DFS(G):
  unmark all v ∈ V
  t ← 0
  for each v ∈ V
    if v is unmarked
      t ← Explore(G, v, t)
    end if
  end for
Explore(G, v, t):
  mark v
  t ← t + 1
  d[v] ← t
  for each (v, w) ∈ E
    if w is unmarked
      t ← Explore(G, w, t)
    end if
  end for
  t ← t + 1
  f[v] ← t
  return t

Suppose that the input directed graph is a directed acyclic graph (DAG).

For an edge , which of the following options will NEVER be correct?

GATE 2026 CS1 question 50: Two side-by-side pseudocode blocks (not a diagram): the left block, DFS(G), unmarks all vertices, initializes t=0, and…Tap to open full size
Figure from the GATE 2026 CS1 paper. It is part of the question.
Figure description

Two side-by-side pseudocode blocks (not a diagram): the left block, DFS(G), unmarks all vertices, initializes t=0, and for each unmarked vertex calls Explore, updating t with the return value. The right block, Explore(G, v, t), marks v, increments t, sets d[v]=t, iterates over all out-edges (v,w) of v, recursively calling Explore(G,w,t) if w is unmarked (updating t), then after the loop increments t, sets f[v]=t, and returns t.

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
GATE 2026 CS1 Q.50: answer and solution

GATE 2026 CS1 Q.55

GATE 2026 · CS1Q.55 · 2 marks · MSQ

An undirected, unweighted, simple graph is said to be 2-colorable if there exists a function such that for every , .

Which of the following statements about 2-colorable graphs is/are true?

  1. (A)

    If is 2-colorable, then may contain cycles of odd length

  2. (B)

    If is 2-colorable, then may contain cycles of even length

  3. (C)

    An optimal algorithm for testing whether is 2-colorable runs in time , if is represented as an adjacency list

  4. (D)

    An optimal algorithm for testing whether is 2-colorable runs in time , if is represented as an adjacency list

Answer and solution
See the question in the paper
GATE 2026 CS1 Q.55: answer and solution

GATE 2026 CS2 Q.36

GATE 2026 · CS2Q.36 · 2 marks · MCQ

Consider a complete graph with vertices (). Note that multiple spanning trees can be constructed over . Each of these spanning trees is represented as a set of edges. The Jaccard coefficient between any two sets is defined as the ratio of the size of the intersection of the two sets to the size of the union of the two sets.

Which one of the following options gives the lowest possible value for the Jaccard coefficient between any two spanning trees of ?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.36: answer and solution

GATE 2026 CS2 Q.37

GATE 2026 · CS2Q.37 · 2 marks · MCQ

Let be a weighted directed acyclic graph with edges and vertices. Given and a source vertex in , which one of the following options gives the worst case time complexity of the fastest algorithm to find the lengths of shortest paths from to all vertices that are reachable from in ?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.37: answer and solution

GATE 2026 DA Q.40

GATE 2026 · DAQ.40 · 2 marks · MCQ

Consider a directed graph , where is the finite set of vertices and is the set of directed edges between the vertices. may contain cycles but there is no self-loop. Further, may not be strongly connected.

Let be the graph obtained by reversing the directions of all the edges in without changing the set of vertices.

Assume that Breadth First Search (BFS) or Depth First Search (DFS) from any given vertex of a graph visits only the reachable vertices from in that graph.

Which of the following statements must always be true, regardless of the structure of ?

  1. (A)

    If is a reachable vertex in the BFS of from , then is also a reachable vertex in the DFS of from .

  2. (B)

    In , the BFS traversal from will visit exactly the same set of vertices as the DFS from in .

  3. (C)

    The order of vertices visited in the BFS of from is the reverse of the order of vertices visited in the DFS of from .

  4. (D)

    If is a reachable vertex in the DFS of from , then is also a reachable vertex in the BFS of from .

Answer and solution
See the question in the paper
GATE 2026 DA Q.40: answer and solution

GATE 2025 CS1 Q.18

GATE 2025 · CS1Q.18 · 1 mark · MCQ

Let be any undirected graph with positive edge weights, and be a minimum spanning tree of . For any two vertices, and , let and be the shortest distances between and in and , respectively. Which ONE of the options is CORRECT for all possible , , and ?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.18: answer and solution

GATE 2025 CS1 Q.43

GATE 2025 · CS1Q.43 · 2 marks · MCQ

Let be an undirected and unweighted graph with 100 vertices. Let denote the number of edges in a shortest path between vertices and in . Let the maximum value of , such that , be 30. Let be any breadth-first-search tree of . Which ONE of the given options is CORRECT for every such graph ?

  1. (A)

    The height of is exactly 15.

  2. (B)

    The height of is exactly 30.

  3. (C)

    The height of is at least 15.

  4. (D)

    The height of is at least 30.

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.43: answer and solution

GATE 2025 CS1 Q.64

GATE 2025 · CS1Q.64 · 2 marks · NAT

The maximum value of such that the edge between the nodes B and C is included in every minimum spanning tree of the given graph is ________ . (answer in integer)

Graph (4 vertices A, B, C, D arranged as a square with both diagonals drawn, i.e. ):
- A connects to B with weight 7 (top edge)
- A connects to D with weight 6 (left edge)
- D connects to C with weight 8 (bottom edge)
- B connects to C with weight (right edge, unknown)
- B connects to D with weight 1 (one diagonal)
- A connects to C with weight 3 (other diagonal)

GATE 2025 CS1 question 64: A square-shaped graph with 4 labelled circular nodes: A (top-left), B (top-right), D (bottom-left), C (bottom-right).Tap to open full size
Figure from the GATE 2025 CS1 paper. It is part of the question.
Figure description

A square-shaped graph with 4 labelled circular nodes: A (top-left), B (top-right), D (bottom-left), C (bottom-right). Edges: A–B labelled 7 (top side), A–D labelled 6 (left side), D–C labelled 8 (bottom side), B–C labelled x (right side). Two diagonals cross in the middle without meeting at a vertex: B–D labelled 1 (label near its upper half) and A–C labelled 3 (label near its lower half, towards C).

Answer and solution
GATE 2025 CS1 Q.64: answer and solution

GATE 2025 CS2 Q.29

GATE 2025 · CS2Q.29 · 1 mark · MSQ

Which of the following statements regarding Breadth First Search (BFS) and Depth First Search (DFS) on an undirected simple graph is/are TRUE?

  1. (A)

    A DFS tree of is a Shortest Path tree of .

  2. (B)

    Every non-tree edge of with respect to a DFS tree is a forward/back edge.

  3. (C)

    If is a non-tree edge of with respect to a BFS tree, then the distances from the source vertex to and in the BFS tree are within of each other.

  4. (D)

    Both BFS and DFS can be used to find the connected components of .

Answer and solution
See the question in the paper
GATE 2025 CS2 Q.29: answer and solution

GATE 2025 CS2 Q.37

GATE 2025 · CS2Q.37 · 2 marks · MCQ

Let be an edge-weighted undirected graph with positive edge weights. Suppose a positive constant is added to the weight of every edge.

Which ONE of the following statements is TRUE about the minimum spanning trees (MSTs) and shortest paths (SPs) in before and after the edge weight update?

  1. (A)

    Every MST remains an MST, and every SP remains an SP.

  2. (B)

    MSTs need not remain MSTs, and every SP remains an SP.

  3. (C)

    Every MST remains an MST, and SPs need not remain SPs.

  4. (D)

    MSTs need not remain MSTs, and SPs need not remain SPs.

Answer and solution
See the question in the paper
GATE 2025 CS2 Q.37: answer and solution

GATE 2025 CS2 Q.59

GATE 2025 · CS2Q.59 · 2 marks · NAT

Consider the following algorithm someAlgo that takes an undirected graph G as input.

someAlgo(G)
  1. Let v be any vertex in G. Run BFS on G starting at v. Let u be a vertex in G at maximum distance from v as given by the BFS.
  2. Run BFS on G again with u as the starting vertex. Let z be the vertex at maximum distance from u as given by the BFS.
  3. Output the distance between u and z in G.

The output of someAlgo() for the tree shown in the given figure is ___________. (Answer in integer)

GATE 2025 CS2 question 59: An unrooted tree with 14 vertices and 13 edges.Tap to open full size
Figure from the GATE 2025 CS2 paper. It is part of the question.
Figure description

An unrooted tree with 14 vertices and 13 edges. Two internal hub vertices P and Q (each degree 4) are joined directly by one edge. P also connects to: a leaf L1; a degree-3 vertex M, which itself connects to two further leaves T1 and R1; and a path P-L2-L3 (L2 degree 2) ending in leaf L3. Q also connects to: two leaves B1 and B2; and a path Q-R2-R3-R4 where R2 is degree 3 (also branching to leaf T2) and R3 is degree 2, ending in leaf R4. No vertex labels are printed in the figure; positions only show dots and connecting line segments.

Answer and solution
GATE 2025 CS2 Q.59: answer and solution

GATE 2025 DA Q.58

GATE 2025 · DAQ.58 · 2 marks · MSQ

Let be a simple, unweighted, and undirected graph. A subset of the vertices and edges of are shown below.

It is given that is a shortest path between and ; is a shortest path between and ; is a shortest path between and . Which of the following is/are NOT the edges of ?

GATE 2025 DA question 58: Eight vertices in two rows.Tap to open full size
Figure from the GATE 2025 DA paper. It is part of the question.
Figure description

Eight vertices in two rows. Top row left to right: a, b, c, d. Bottom row left to right: e, f, g, h. Drawn edges: a-b, b-c, c-d (top row path); e-f, f-g, g-h (bottom row path); diagonal a-f (from a down-right to f); diagonal c-f (from c down-left to f); diagonal c-h (from c down-right to h). No other edges are drawn.

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
GATE 2025 DA Q.58: answer and solution

GATE 2025 DA Q.65

GATE 2025 · DAQ.65 · 2 marks · NAT

Consider a directed graph , where and . Suppose the adjacency list of each vertex is in decreasing order of vertex number, and depth-first search (DFS) is performed at vertex 0. The number of vertices that will be discovered after vertex 50 is ______ (Answer in integer)

Answer and solution
See the question in the paper
GATE 2025 DA Q.65: answer and solution

GATE 2024 CS1 Q.45

GATE 2024 · CS1Q.45 · 2 marks · MSQ

Let be a directed graph and a depth first search (DFS) spanning tree in that is rooted at a vertex . Suppose is also a breadth first search (BFS) tree in , rooted at . Which of the following statements is/are TRUE for every such graph and tree ?

  1. (A)

    There are no back-edges in with respect to the tree

  2. (B)

    There are no cross-edges in with respect to the tree

  3. (C)

    There are no forward-edges in with respect to the tree

  4. (D)

    The only edges in are the edges in

Answer and solution
See the question in the paper
GATE 2024 CS1 Q.45: answer and solution

GATE 2024 CS2 Q.51

GATE 2024 · CS2Q.51 · 2 marks · MSQ

Let be an undirected connected graph in which every edge has a positive integer weight. Suppose that every spanning tree in has even weight. Which of the following statements is/are TRUE for every such graph ?

  1. (A)

    All edges in have even weight

  2. (B)

    All edges in have even weight OR all edges in have odd weight

  3. (C)

    In each cycle in , all edges in have even weight

  4. (D)

    In each cycle in , either all edges in have even weight OR all edges in have odd weight

Answer and solution
See the question in the paper
GATE 2024 CS2 Q.51: answer and solution

GATE 2024 CS2 Q.59

GATE 2024 · CS2Q.59 · 2 marks · NAT

The number of distinct minimum-weight spanning trees of the following graph is ____.

Graph description: Vertices a, b, c, d, e, f, g. Edges and weights:
- a-b: 1
- a-f: 1
- a-g: 2
- b-c: 3
- b-g: 2
- c-g: 2
- c-d: 1
- g-f: 2
- g-e: 2
- g-d: 2
- f-e: 3
- e-d: 1

GATE 2024 CS2 question 59: An undirected weighted graph with 7 vertices: a, b, c, d, e, f, g.Tap to open full size
Figure from the GATE 2024 CS2 paper. It is part of the question.
Figure description

An undirected weighted graph with 7 vertices: a, b, c, d, e, f, g. Positions roughly: a (far left), b (top left), c (top right), d (far right), f (bottom left), e (bottom right), g (center). Edges: a-b weight 1, a-f weight 1, a-g weight 2, b-c weight 3, b-g weight 2, c-g weight 2, c-d weight 1, g-f weight 2, g-e weight 2, g-d weight 2, f-e weight 3, e-d weight 1. g is connected to all six other vertices (a,b,c,d,e,f), each with weight 2.

Answer and solution
GATE 2024 CS2 Q.59: answer and solution

GATE 2024 DA Q.14

GATE 2024 · DAQ.14 · 1 mark · MCQ

Consider performing depth-first search (DFS) on an undirected and unweighted graph starting at vertex . For any vertex in , is the length of the shortest path from to . Let be an edge in such that . If the edge is explored first in the direction from to during the above DFS, then becomes a ______ edge.

  1. (A)

    tree

  2. (B)

    cross

  3. (C)

    back

  4. (D)

    gray

Official answer
See the question in the paper
GATE 2024 DA Q.14: official answer

GATE 2024 DA Q.51

GATE 2024 · DAQ.51 · 2 marks · MSQ

Consider the directed acyclic graph (DAG) below. Which of the following is/are valid vertex orderings that can be obtained from a topological sort of the DAG?

GATE 2024 DA question 51: A DAG on seven labelled circular nodes P, R, Q, S, V, U, T.Tap to open full size
Figure from the GATE 2024 DA paper. It is part of the question.
Figure description

A DAG on seven labelled circular nodes P, R, Q, S, V, U, T. Directed edges: P -> Q, R -> Q (P and R sit at the top, both pointing down into Q); Q -> S and Q -> V (S on the lower left, V on the lower right); S -> U (U directly below S); V -> T (T directly below V). There are six edges in total.

  1. (A)

    P Q R S T U V

  2. (B)

    P R Q V S U T

  3. (C)

    P Q R S V U T

  4. (D)

    P R Q S V T U

Answer and solution
GATE 2024 DA Q.51: answer and solution

GATE 2023 CS Q.56

GATE 2023 · CSQ.56 · 2 marks · NAT

Let . Let denote the powerset of . Consider an undirected graph whose vertex set is . For any , is an edge in if and only if (i) , and (ii) either or . For any vertex in , the set of all possible orderings in which the vertices of can be visited in a Breadth First Search (BFS) starting from is denoted by .

If denotes the empty set, then the cardinality of is ______.

Answer and solution
See the question in the paper
GATE 2023 CS Q.56: answer and solution

GATE 2022 CS Q.49

GATE 2022 · CSQ.49 · 2 marks · MSQ

Consider a simple undirected weighted graph , all of whose edge weights are distinct. Which of the following statements about the minimum spanning trees of is/are TRUE?

  1. (A)

    The edge with the second smallest weight is always part of any minimum spanning tree of .

  2. (B)

    One or both of the edges with the third smallest and the fourth smallest weights are part of any minimum spanning tree of .

  3. (C)

    Suppose be such that and . Consider the edge with the minimum weight such that one of its vertices is in and the other in . Such an edge will always be part of any minimum spanning tree of .

  4. (D)

    can have multiple minimum spanning trees.

Answer and solution
See the question in the paper
GATE 2022 CS Q.49: answer and solution

GATE 2020 CS Q.31

GATE 2020 · CSQ.31 · 2 marks · MCQ

Let be a weighted undirected graph and let be a Minimum Spanning Tree (MST) of maintained using adjacency lists. Suppose a new weighted edge is added to . The worst case time complexity of determining if is still an MST of the resultant graph is

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2020 CS Q.31: answer and solution

GATE 2020 CS Q.40

GATE 2020 · CSQ.40 · 2 marks · MCQ

Let be a directed, weighted graph with weight function .

For some function , for each edge , define as

Which one of the options completes the following sentence so that it is TRUE?

"The shortest paths in under are shortest paths under too, ___."

  1. (A)

    for every

  2. (B)

    if and only if , is positive

  3. (C)

    if and only if , is negative

  4. (D)

    if and only if is the distance from to in the graph obtained by adding a new vertex to and edges of zero weight from to every vertex of

Answer and solution
See the question in the paper
GATE 2020 CS Q.40: answer and solution

GATE 2018 CS Q.30

GATE 2018 · CSQ.30 · 2 marks · MCQ

Let be a simple undirected graph. Let be a depth first search tree of . Let be a breadth first search tree of . Consider the following statements.

(I) No edge of is a cross edge with respect to . (A cross edge in is between two nodes neither of which is an ancestor of the other in .)

(II) For every edge of , if is at depth and is at depth in , then .

Which of the statements above must necessarily be true?

  1. (A)

    I only

  2. (B)

    II only

  3. (C)

    Both I and II

  4. (D)

    Neither I nor II

Answer and solution
See the question in the paper
GATE 2018 CS Q.30: answer and solution

GATE 2018 CS Q.47

GATE 2018 · CSQ.47 · 2 marks · NAT

Consider the following undirected graph G. Choose a value for x that will maximize the number of minimum weight spanning trees (MWSTs) of G. The number of MWSTs of G for this value of x is ______.

GATE 2018 CS question 47: An undirected weighted graph with 5 vertices arranged as: a top vertex (T), a left vertex (L), a right vertex (R), and two…Tap to open full size
Figure from the GATE 2018 CS paper. It is part of the question.
Figure description

An undirected weighted graph with 5 vertices arranged as: a top vertex (T), a left vertex (L), a right vertex (R), and two bottom vertices — bottom-left (A) and bottom-right (B). Edges: T–L weight 4; T–R weight x; T–A weight 1 (a diagonal from T down to A); T–B weight 3 (a diagonal from T down to B); L–A weight 4; A–B weight 4 (bottom edge connecting the two bottom vertices); B–R weight 5. Total 7 edges, 5 vertices.

Answer and solution
GATE 2018 CS Q.47: answer and solution

PRACTICE

5 questions to test yourself

PRACTICE 11 mark · MCQ

A depth-first search is run on a connected undirected graph. Each edge is classified the first time it is examined, from either endpoint, using the tree/back/forward/cross scheme defined for directed graphs. Which statement is correct?

  1. (A)

    Only tree edges can occur, whatever the graph.

  2. (B)

    Only tree edges and back edges can occur; back edges occur exactly when the graph has a cycle.

  3. (C)

    Tree, back and forward edges can occur, but never cross edges.

  4. (D)

    All four types can occur.

Answer and solution

Answer: (B)

  1. Take any edge (u,v) and name its endpoints so that d[u] < d[v]. When u is discovered, v is still WHITE, and u examines every neighbour, including v, before it finishes. So v is discovered before u finishes, which makes v a descendant of u (white-path theorem).

  2. Case 1: the edge is first examined from u. If v had already been discovered at that moment, it would have been discovered during u's exploration, so it would already have finished and examined all its own neighbours, including u, earlier. That contradicts 'first examined from u'. So v is WHITE and (u,v) is a tree edge.

  3. Case 2: the edge is first examined from v. At that moment u is an ancestor of v that has not yet finished, so u is GRAY and (v,u) is a back edge.

  4. So every edge is a tree edge or a back edge; forward and cross edges never occur. This rules out C and D.

  5. Tree edges alone form a spanning tree with V−1 edges. Any further edge is a back edge, and it exists exactly when the graph has a cycle. So A is false in general and B is correct.

PRACTICE 21 mark · NAT

A connected, undirected, weighted graph has exactly 12 vertices. What is the number of edges in any minimum spanning tree of this graph?

Answer and solution

Answer:

  1. A spanning tree is a subgraph that is a tree and contains all V vertices.

  2. Every tree on V vertices has exactly V−1 edges. This does not depend on the edge weights, so it holds for every spanning tree, minimum or not.

  3. Here V = 12, so every MST of this graph has 12 − 1 = 11 edges.

PRACTICE 32 marks · MSQ

Which of the following statements about Dijkstra's single-source shortest-path algorithm on a directed graph are TRUE?

  1. (A)

    It is guaranteed to produce correct shortest-path distances even when some edge weights are negative, provided the graph has no negative-weight cycle.

  2. (B)

    Using a binary min-heap as the priority queue (with decrease-key), it runs in O((V+E) log V) time.

  3. (C)

    It is a greedy algorithm: at every step it permanently finalises the not-yet-finalised vertex with the smallest tentative distance.

  4. (D)

    If the same positive constant is added to every edge weight, the shortest path from the source to every vertex stays the same path.

Answer and solution

Answer: (B), (C)

  1. A is FALSE. Dijkstra finalises a vertex when it is extracted and never propagates a later improvement to it. A negative edge found later can lower the true distance, and the graph needs no cycle for this to happen. The worked example (A→B 1, A→C 2, C→B −5, B→D 2) is acyclic, yet Dijkstra reports dist[D] = 3 when the true value is −1.

  2. B is TRUE. There are V extract-min operations and at most E decrease-key operations, each O(log V) on a binary heap, giving O((V+E) log V).

  3. C is TRUE. This is exactly the greedy choice in the algorithm's main step.

  4. D is FALSE. Take the edges s→t (5), s→a (2) and a→t (2). The shortest path from s to t is s→a→t with length 4. Add 2 to every weight: s→t becomes 7 and s→a→t becomes 4 + 2 + 2 = 8, so the shortest path is now the direct edge. Adding c raises a k-edge path by k·c, which penalises paths with more edges.

  5. The correct options are B and C.

PRACTICE 42 marks · NAT

A connected, undirected, weighted graph has 6 vertices {A, B, C, D, E, F} and 9 edges with weights: A–B = 3, A–C = 1, B–C = 7, B–D = 5, C–D = 2, C–E = 6, D–E = 4, D–F = 8, E–F = 9. What is the total weight of its minimum spanning tree?

Answer and solution

Answer:

  1. Sort the edges by weight: A–C 1, C–D 2, A–B 3, D–E 4, B–D 5, C–E 6, B–C 7, D–F 8, E–F 9. All weights are distinct, so the MST is unique.

  2. Kruskal: add A–C (1), giving the set {A,C}. Add C–D (2), giving {A,C,D}. Add A–B (3), giving {A,B,C,D}. Add D–E (4), giving {A,B,C,D,E}.

  3. B–D (5): B and D are in the same set, so discard it (it would form a cycle). C–E (6) and B–C (7) are discarded for the same reason.

  4. D–F (8): F is still in its own set, so add it. Now 5 = V − 1 edges have been added, and the MST is complete.

  5. Total = 1 + 2 + 3 + 4 + 8 = 18.

  6. Check with Prim from F: F joins first; then D (key 8); then C (2, via D); then A (1, via C); then B (3, via A); then E (4, via D). Total 8 + 2 + 1 + 3 + 4 = 18, which agrees.

PRACTICE 52 marks · MCQ

A directed weighted graph has at least one negative-weight edge, but it is guaranteed that no negative-weight cycle is reachable from the source vertex . Which algorithm(s) below are guaranteed to correctly compute the shortest-path distance from to every other vertex?

  1. (A)

    Bellman-Ford only

  2. (B)

    Dijkstra only

  3. (C)

    Both Dijkstra and Bellman-Ford

  4. (D)

    Neither — BFS must be used instead

Answer and solution

Answer: (A)

  1. Dijkstra's correctness relies on the fact that once a vertex is extracted with the smallest tentative distance, no later relaxation can lower it. That holds only when every edge weight is non-negative. A single negative edge can break it even without any cycle, as the worked example A→B 1, A→C 2, C→B −5, B→D 2 shows. So Dijkstra is not guaranteed to be correct here.

  2. Bellman-Ford relaxes every edge in each of V−1 rounds and never treats a distance as final early. Because no negative-weight cycle is reachable from s, every shortest path has at most V−1 edges, so V−1 rounds give the correct distances.

  3. BFS ignores edge weights and is correct only for unweighted graphs, so D is wrong.

  4. Only Bellman-Ford is guaranteed to be correct: option A.

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE CS

graphs … Graph traversals, minimum spanning trees, shortest paths

GATE DA

introduction to graph theory; basic graph algorithms: traversals and shortest path

Preparing in Kolkata? IAE Academy's course for GATE CSE or GATE DA.