Module 6 · 15 min read · Free chapter
Graph traversal, shortest paths and NP-completeness basics
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.
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 with adjacency lists. With an adjacency matrix, finding the neighbours of one vertex scans a whole row of entries, so the time becomes . 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 is when v is first reached, and the finish time 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 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 .
- A cross edge goes to a black vertex v that is neither an ancestor nor a descendant, so .
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 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 . The first runs DFS and lists vertices in decreasing order of finish time, since in a DAG every edge has . 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 , then a better route to v goes through u, so set and remember u as v's parent.
Dijkstra's algorithm handles the case where all weights are non-negative. It starts with 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 and . B is nearest, and relaxing B→A gives and B→C gives .
A is nearest next, and A→C improves C to . Then C is finished and C→D sets , 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 , giving . With a plain array, each of the extractions scans entries, giving , which is better for dense graphs; a Fibonacci heap gives .
Why negative edges break it. Take S→A 2, S→B 3 and B→A with weight . Dijkstra finishes A first with distance 2, but the route S→B→A costs . 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, times. A shortest path with no cycle has at most edges, and after pass every shortest path of up to edges is correct. So after passes all distances are final, and the time is .
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 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 be the shortest distance from to using only vertices 1 to as intermediate stops. Either the best such path avoids , or it goes through once, so .
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 time, and one matrix updated in place gives space. Floyd–Warshall allows negative edges but not negative cycles, and a negative cycle shows up as a negative diagonal entry . The loop must be the outermost, because each phase needs the complete results of phase .
| Method | Problem | Negative edges? | Time |
|---|---|---|---|
| BFS | single source, unweighted | not applicable | |
| Dijkstra | single source | no | |
| Bellman–Ford | single source | yes, detects negative cycles | |
| DAG relaxation | single source on a DAG | yes | |
| Floyd–Warshall | all pairs | yes, but no negative cycles |
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 or . 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 ?". 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 . Whether is the most famous open question in computer science. Most experts believe , but there is no proof either way.
To compare problems we use reductions. A polynomial-time reduction from A to B, written , 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 .
| 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 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:
- Trace BFS, DFS or Dijkstra on a given graph and show the queue, stack or distance table at each step.
- Compare shortest-path algorithms on the kinds of graphs they handle and their running times.
- Explain a structural idea, such as DFS edge types, topological sort or negative cycles.
- 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).
- 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)
- Explain why Dijkstra's algorithm can fail with a negative edge and how Bellman–Ford handles such graphs. (10 marks)
- 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 and that whether 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 with lists.
- DFS uses a stack or recursion, records discovery and finish times and runs in 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 with a binary heap or with an array.
- Bellman–Ford relaxes every edge times in and detects negative cycles.
- Floyd–Warshall finds all-pairs shortest paths in with 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.