Computer Science and IT‹›⌂ 0:00 studied

Module 6 · 15 min read · Free chapter

Graph traversal, shortest paths and NP-completeness basics

In short

BFS and DFS each run in Θ(V + E) on adjacency lists; BFS finds fewest-edge paths and DFS finds cycles through back edges. Dijkstra needs non-negative weights, Bellman–Ford handles negative edges in Θ(VE), and Floyd–Warshall gives all pairs in Θ(V³). NP problems are those whose answers can be checked in polynomial time.

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

Start from zero: spreading news and exploring lanes

Suppose a wedding date is fixed in one house of a mohalla. That family tells its immediate neighbours first, those neighbours tell theirs, and so the news spreads ring by ring. Everyone one step away hears it first, then everyone two steps away, and so on.

Now picture a visitor exploring the lanes of an old city. He walks down one lane as far as it goes, turns into the next unseen lane, and keeps going deeper. Only at a dead end does he come back to the last turning and try a lane he has not yet walked.

These are the two basic ways to visit every vertex of a graph, which is a set of points joined by links. Spreading ring by ring is breadth-first search (BFS), and going deep first is depth-first search (DFS). Most graph algorithms, from shortest routes to deciding the order of tasks, are built on one of the two.

Why it matters. Railway route finders, map apps, social networks and build tools all walk graphs. GATE asks about traversal orders, shortest paths and their running times every year.

Breadth-first search

BFS starts at a source vertex S, marks it visited and puts it in a queue. It then repeatedly removes the vertex at the front of the queue and puts every unvisited neighbour at the back, marking each one visited and recording its distance as one more than the current vertex. Because a queue is first-in, first-out, all vertices at distance 1 come out before any at distance 2.

BFS(G, s):
    for each vertex v: dist[v] = infinity
    dist[s] = 0; Q = queue containing s
    while Q is not empty:
        u = dequeue(Q)
        for each neighbour v of u:
            if dist[v] == infinity:
                dist[v] = dist[u] + 1; parent[v] = u
                enqueue(Q, v)

Worked example. Take the undirected graph with edges S–A, S–B, A–C, B–C and C–D, with neighbours listed in alphabetical order. BFS from S visits S, then A and B at distance 1, then C at distance 2, and finally D at distance 3. The parent links S→A, S→B, A→C and C→D form the BFS tree.

In an unweighted graph, the path along BFS-tree parents is a shortest path in number of edges. That is why BFS is the right tool for "fewest hops" questions, such as the fewest flight changes between two cities.

Each vertex enters the queue at most once, and each adjacency list is scanned once, so BFS takes Θ(V+E)\Theta(V + E) with adjacency lists. With an adjacency matrix, finding the neighbours of one vertex scans a whole row of VV entries, so the time becomes Θ(V2)\Theta(V^2). How graphs are stored is covered with graph representation.

Why it matters. BFS gives levels and shortest hop counts, tests whether a graph is connected and checks whether it is bipartite. Exam questions often ask for a BFS order or for which vertex sits at which level.

Depth-first search, edge types and topological sort

DFS visits a vertex, then immediately visits one of its unvisited neighbours, and so on, going as deep as possible. When a vertex has no unvisited neighbour left, DFS backtracks to the vertex it came from. A recursive function does this naturally, with the call stack playing the role of the visitor's memory of turnings.

DFS stamps each vertex with two times. The discovery time d[v]d[v] is when v is first reached, and the finish time f[v]f[v] is when all of v's neighbours are done. Colours help too: a vertex is white before discovery, grey while it is being explored and black when it is finished.

In a directed graph, these times sort every edge u→vu \to v into one of four types:

  • A tree edge goes to a white vertex v, which DFS discovers through this edge.
  • A back edge goes to a grey vertex v, an ancestor of u that is still open.
  • A forward edge goes to a black vertex v that is a descendant of u, so d[u]<d[v]d[u] < d[v].
  • A cross edge goes to a black vertex v that is neither an ancestor nor a descendant, so d[v]<d[u]d[v] < d[u].

In an undirected graph only tree edges and back edges can occur. The most useful fact is the cycle test: a directed graph has a cycle if and only if DFS finds a back edge. Like BFS, DFS takes Θ(V+E)\Theta(V + E) with adjacency lists.

Topological sort orders the vertices of a directed acyclic graph (DAG) so that every edge points forward. Take courses as vertices: C programming P before data structures D, D before algorithms A, discrete maths M before A, and A before compilers K. One valid order is M, P, D, A, K, and in all there are 3 valid orders, because M can go anywhere before A.

There are two standard methods, both Θ(V+E)\Theta(V + E). The first runs DFS and lists vertices in decreasing order of finish time, since in a DAG every edge u→vu \to v has f[u]>f[v]f[u] > f[v]. The second, Kahn's method, repeatedly removes a vertex with no incoming edges, and if vertices remain but none has in-degree 0, the graph has a cycle.

Why it matters. Build systems, spreadsheet recalculation and course planning all need a topological order. GATE often gives a DAG and asks how many orders exist or which order is valid.

Dijkstra's algorithm

When edges have weights, such as kilometres or minutes, the fewest edges is no longer the shortest route. The basic step of every shortest-path method is relaxation: if d[u]+w(u,v)<d[v]d[u] + w(u, v) < d[v], then a better route to v goes through u, so set d[v]=d[u]+w(u,v)d[v] = d[u] + w(u, v) and remember u as v's parent.

Dijkstra's algorithm handles the case where all weights are non-negative. It starts with d[S]=0d[S] = 0 and every other distance infinite. It then repeatedly picks the unfinished vertex with the smallest d, marks it finished and relaxes all its outgoing edges; it is a greedy method, because a finished distance is never changed again.

Worked example. The directed edges are S→A 4, S→B 1, B→A 2, A→C 1, B→C 5 and C→D 3. Finishing S sets A=4A = 4 and B=1B = 1. B is nearest, and relaxing B→A gives A=1+2=3A = 1 + 2 = 3 and B→C gives C=6C = 6.

A is nearest next, and A→C improves C to 3+1=43 + 1 = 4. Then C is finished and C→D sets D=7D = 7, and finally D is finished. The shortest distances are S 0, B 1, A 3, C 4 and D 7, and the finishing order is S, B, A, C, D.

The choice of priority queue sets the running time. With a binary heap each extraction and each decrease of a key costs O(log⁡V)O(\log V), giving O((V+E)log⁡V)O((V + E) \log V). With a plain array, each of the VV extractions scans VV entries, giving O(V2)O(V^2), which is better for dense graphs; a Fibonacci heap gives O(E+Vlog⁡V)O(E + V \log V).

Why negative edges break it. Take S→A 2, S→B 3 and B→A with weight −2-2. Dijkstra finishes A first with distance 2, but the route S→B→A costs 3−2=13 - 2 = 1. Once A is finished, the method never revisits it, so it reports the wrong answer.

Why it matters. Dijkstra's method runs inside map apps and network routing protocols. GATE asks for the order of finished vertices, a distance after some steps or the running time with a given data structure.

Bellman–Ford, DAG shortest paths and Floyd–Warshall

Bellman–Ford gives up Dijkstra's greedy choice and simply relaxes every edge, V−1V - 1 times. A shortest path with no cycle has at most V−1V - 1 edges, and after pass ii every shortest path of up to ii edges is correct. So after V−1V - 1 passes all distances are final, and the time is Θ(VE)\Theta(VE).

Bellman–Ford works with negative edge weights. It also detects trouble: if one more pass still lowers some distance, the graph contains a negative-weight cycle reachable from the source. In that case "shortest path" has no meaning, because going round the cycle again always lowers the cost.

If the graph is a DAG, there is a faster way. Relax the outgoing edges of each vertex in topological order, once each. This takes Θ(V+E)\Theta(V + E) and works even with negative weights, because a DAG has no cycles at all.

Floyd–Warshall finds shortest paths between all pairs of vertices. Let d(k)[i][j]d^{(k)}[i][j] be the shortest distance from ii to jj using only vertices 1 to kk as intermediate stops. Either the best such path avoids kk, or it goes through kk once, so d(k)[i][j]=min⁡(d(k−1)[i][j],d(k−1)[i][k]+d(k−1)[k][j])d^{(k)}[i][j] = \min(d^{(k-1)}[i][j], d^{(k-1)}[i][k] + d^{(k-1)}[k][j]).

for k = 1 to V
    for i = 1 to V
        for j = 1 to V
            if d[i][k] + d[k][j] < d[i][j]:
                d[i][j] = d[i][k] + d[k][j]

The three loops give Θ(V3)\Theta(V^3) time, and one V×VV \times V matrix updated in place gives Θ(V2)\Theta(V^2) space. Floyd–Warshall allows negative edges but not negative cycles, and a negative cycle shows up as a negative diagonal entry d[i][i]<0d[i][i] < 0. The kk loop must be the outermost, because each phase kk needs the complete results of phase k−1k - 1.

Method Problem Negative edges? Time
BFS single source, unweighted not applicable Θ(V+E)\Theta(V + E)
Dijkstra single source no O((V+E)log⁡V)O((V + E) \log V)
Bellman–Ford single source yes, detects negative cycles Θ(VE)\Theta(VE)
DAG relaxation single source on a DAG yes Θ(V+E)\Theta(V + E)
Floyd–Warshall all pairs yes, but no negative cycles Θ(V3)\Theta(V^3)

Why it matters. Choosing the right method is half of every shortest-path question. Negative edges rule out Dijkstra, a DAG allows linear time, and "all pairs" on a dense graph points to Floyd–Warshall.

P, NP and NP-completeness at an intro level

Every problem so far has a polynomial-time algorithm, such as Θ(V+E)\Theta(V + E) or Θ(n3)\Theta(n^3). But for some problems, like finding the cheapest tour through all cities, nobody knows any polynomial-time method. Complexity theory sorts problems by this kind of difficulty, and to keep things simple it talks about decision problems, whose answer is yes or no.

P is the class of decision problems that can be solved in polynomial time, such as "is there a path from u to v of length at most kk?". NP is the class whose yes-answers can be checked in polynomial time when someone hands you a proof, called a certificate. For example, "does this graph have a Hamiltonian cycle?" is in NP, because a proposed cycle can be checked quickly.

Every problem in P is also in NP, since you can check an answer by solving the problem yourself, so P⊆NP\mathrm{P} \subseteq \mathrm{NP}. Whether P=NP\mathrm{P} = \mathrm{NP} is the most famous open question in computer science. Most experts believe P≠NP\mathrm{P} \ne \mathrm{NP}, but there is no proof either way.

To compare problems we use reductions. A polynomial-time reduction from A to B, written A≤pBA \le_p B, turns every instance of A into an instance of B with the same answer. Then a fast method for B would give a fast method for A, so B is at least as hard as A.

A problem is NP-hard if every problem in NP reduces to it. It is NP-complete if it is NP-hard and also in NP. The first NP-complete problem was SAT, which asks whether a Boolean formula can be made true, and this result is the Cook–Levin theorem.

After SAT, each new problem B is shown NP-complete in two steps: show that B is in NP, and reduce a known NP-complete problem to B. For example, 3-SAT reduces to vertex cover, so vertex cover is NP-complete. If any one NP-complete problem were solved in polynomial time, every problem in NP would be, and then P=NP\mathrm{P} = \mathrm{NP}.

In P NP-complete
Shortest path Longest simple path (decision form)
Minimum spanning tree Travelling salesman (decision form)
2-SAT 3-SAT
Euler circuit Hamiltonian cycle
Graph 2-colouring Graph 3-colouring

The table shows how a small change can cross the line. Shortest path is easy but longest simple path is hard, an Euler circuit uses every edge and is easy but a Hamiltonian cycle uses every vertex and is hard. The 0/1 knapsack problem is also NP-complete in its decision form, which fits its pseudo-polynomial Θ(nW)\Theta(nW) method.

Why it matters. When a problem turns out to be NP-complete, engineers stop hunting for a perfect fast method and use approximations, heuristics or exponential methods on small inputs. This topic is not named in the GATE 2026 syllabus, but ISRO, NIELIT and university papers still ask it.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about graph algorithms and NP-completeness in four ways:

  1. Trace BFS, DFS or Dijkstra on a given graph and show the queue, stack or distance table at each step.
  2. Compare shortest-path algorithms on the kinds of graphs they handle and their running times.
  3. Explain a structural idea, such as DFS edge types, topological sort or negative cycles.
  4. Define P, NP, NP-hard and NP-complete, and outline how a reduction proves a problem NP-complete.

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

  1. Run BFS and DFS from S on a graph with edges S–A, S–B, A–C, B–C and C–D, and draw both trees. (10 marks)
  2. Explain why Dijkstra's algorithm can fail with a negative edge and how Bellman–Ford handles such graphs. (10 marks)
  3. Define P, NP and NP-complete, and explain how you would prove that a new problem is NP-complete. (15 marks)

Answer plan for question 3.

  • Define P as the class of decision problems that a deterministic algorithm solves in polynomial time.
  • Define NP as the class of decision problems whose yes-instances have certificates that can be checked in polynomial time, and give Hamiltonian cycle as an example.
  • State that P⊆NP\mathrm{P} \subseteq \mathrm{NP} and that whether P=NP\mathrm{P} = \mathrm{NP} is still unknown.
  • Define a polynomial-time reduction from A to B and explain that it makes B at least as hard as A.
  • Define NP-hard and NP-complete, and name SAT as the first NP-complete problem by the Cook–Levin theorem.
  • Describe the two-step proof for a new problem B: show that B is in NP, then reduce a known NP-complete problem such as 3-SAT to B in polynomial time.

Quick revision

  • BFS uses a queue, visits by levels, gives fewest-edge paths and runs in Θ(V+E)\Theta(V + E) with lists.
  • DFS uses a stack or recursion, records discovery and finish times and runs in Θ(V+E)\Theta(V + E) with lists.
  • A directed graph has a cycle if and only if DFS finds a back edge.
  • Undirected DFS gives only tree and back edges, while directed DFS can also give forward and cross edges.
  • A topological order exists only for a DAG and comes from decreasing finish times or from Kahn's method.
  • Dijkstra needs non-negative weights and runs in O((V+E)log⁡V)O((V + E) \log V) with a binary heap or O(V2)O(V^2) with an array.
  • Bellman–Ford relaxes every edge V−1V - 1 times in Θ(VE)\Theta(VE) and detects negative cycles.
  • Floyd–Warshall finds all-pairs shortest paths in Θ(V3)\Theta(V^3) with kk as the outer loop.
  • P problems are solvable in polynomial time, and NP problems are verifiable in polynomial time.
  • An NP-complete problem is in NP and NP-hard, and SAT was the first one.

Check yourself

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

  1. Breadth-first search uses which data structure to hold the vertices waiting to be explored?

  2. BFS on a graph stored as an adjacency matrix takes:

  3. In the graph with edges S–A, S–B, A–C, B–C and C–D, the BFS level of D from S is:

  4. DFS on a graph with VV vertices and EE edges, stored as adjacency lists, takes:

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

  6. Which edge types can DFS produce on an undirected graph?

  7. A DAG has edges P → D, D → A, M → A and A → K. How many topological orders does it have?

  8. With edges S→A 4, S→B 1, B→A 2, A→C 1, B→C 5 and C→D 3, Dijkstra from S gives the distance to D as:

  9. Dijkstra's algorithm may give wrong answers when the graph has:

  10. Bellman–Ford on a graph with VV vertices and EE edges takes:

  11. After V−1V - 1 passes of Bellman–Ford, one more pass still reduces a distance. This shows:

  12. Floyd–Warshall computes all-pairs shortest paths in:

  13. NP is best described as the class of decision problems that:

  14. To prove that a new problem B is NP-hard, you should:

  15. Which of these problems is known to be in P?

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

Why does Dijkstra fail with negative edge weights?

Once a vertex is finalised it is never revisited, so a negative edge found later cannot lower its distance. Use Bellman–Ford instead.

How does Bellman–Ford detect a negative cycle?

After V − 1 passes all distances are final unless a negative cycle is reachable. If one more pass still lowers a distance, such a cycle exists.

What is the difference between NP-hard and NP-complete?

An NP-hard problem is at least as hard as every problem in NP. It is NP-complete when it is also in NP itself, like 3-SAT.

Which graph problem needs a topological sort?

Ordering tasks with dependencies in a directed acyclic graph, such as course prerequisites. It exists only when the graph has no cycle.

More in this module: Algorithms

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 Algorithms (IIT Kharagpur, 106105164): graph algorithms, shortest paths, NP-completeness
  3. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): BFS, DFS, topological sort, Dijkstra, Bellman-Ford, Floyd-Warshall