📘 CodingMarble Learn

Graph Algorithms

A graph is a set of vertices joined by edges, which can carry weights. Breadth-first search (BFS) explores in layers using a queue and finds the fewest-edge path. Depth-first search (DFS) goes deep using a stack or recursion and backtracks. Trees can be traversed pre-order, in-order and post-order. Dijkstra's algorithm finds shortest paths from one vertex when weights are non-negative. Kruskal's and Prim's algorithms build a minimum spanning tree. Route inspection finds the shortest closed route using every edge; the travelling salesperson problem asks for the shortest tour of every vertex. In a flow network, the maximum flow equals the capacity of the minimum cut.

🎬 Step-by-step story

  1. Here is a graph: six towns (vertices) joined by nine roads (edges). Each road has a weight, its length.
  2. Breadth-first search starts at A and visits in layers: first all neighbours, then their neighbours. It uses a queue.
  3. Depth-first search starts at A and goes as deep as it can down one path, then backtracks. It uses a stack.
  4. Dijkstra's algorithm finds the shortest distance from A to every town, fixing the nearest unfixed town each time.
  5. A minimum spanning tree links all towns with the least total road. Kruskal picks the cheapest edges that make no loop.
  6. Free play: choose an algorithm and a start town, and watch it run step by step.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Is a graph the same as a chart or a plotted graph?

No. Here a graph is just dots (vertices) and lines (edges). Positions do not matter, only what is joined to what.

Why does BFS need a queue?

A queue serves first come, first served, so all vertices of one layer are taken before any of the next layer.

How does DFS know where to go back to?

The stack remembers the path. At a dead end it pops the last vertex and tries its next unvisited neighbour.

Why is the shortest route to B not the direct road A–B?

A–B is 4 km, but A–C–B is 2 + 1 = 3 km. Dijkstra compares totals, not the number of roads.

Why does Kruskal skip a cheap edge?

If both ends are already linked in the tree, the edge would make a loop and add weight without joining anything new.

Does the start town change the MST?

No. The MST depends only on the edge weights. Try MST with different starts in free play; BFS, DFS and Dijkstra do change.

Graphs and how computers store them

A graph has vertices (nodes) and edges (links). Edges may be directed (one-way arrows) and may have weights (distance, cost, time or capacity).

The degree of a vertex is the number of edges at it. In the 3D graph, C has degree 4.

Traversals: breadth-first and depth-first

Breadth-first search (BFS)

  1. Put the start vertex in a queue and mark it visited.
  2. Take the vertex at the front of the queue.
  3. Add each unvisited neighbour to the back of the queue and mark it.
  4. Repeat until the queue is empty.

BFS finds the path with the fewest edges in an unweighted graph. Uses: shortest route in a maze, friends of friends, web crawlers.

Depth-first search (DFS)

  1. Visit the start vertex and mark it.
  2. Go to an unvisited neighbour and repeat from there (push onto a stack, or use recursion).
  3. At a dead end, backtrack (pop) to the last vertex with an unvisited neighbour.

Uses: solving mazes and puzzles, finding cycles, checking whether a graph is connected, topological sort of tasks.

Both take time proportional to V + E (vertices + edges) with an adjacency list.

Tree traversals: pre-order, in-order, post-order

A tree is a connected graph with no cycles. For a binary tree, DFS can visit the root at three different moments:

Example: tree with root 8, left child 3 (children 1 and 6), right child 10. Pre-order: 8, 3, 1, 6, 10. In-order: 1, 3, 6, 8, 10. Post-order: 1, 6, 3, 10, 8.

Dijkstra's shortest-path algorithm

  1. Give the start vertex distance 0 and all others ∞.
  2. Pick the unfixed vertex with the smallest distance and fix it (its distance is now final).
  3. For each neighbour, if (fixed distance + edge weight) is smaller than its current distance, update it and note where it came from.
  4. Repeat until all vertices are fixed. Trace back the "came from" notes to get the route.

In the 3D graph from A: A = 0, C = 2, B = 3 (via C, not the direct road of 4), D = 8, E = 10, F = 13. Dijkstra only works when no weight is negative. With a priority queue it runs in about (V + E) log V time.

Minimum spanning trees, route inspection and the travelling salesperson

Minimum spanning tree (MST)

A spanning tree joins all V vertices with V − 1 edges and no cycles. The MST has the smallest total weight.

In the 3D graph: BC 1, AC 2, DE 2, EF 3, BD 5 → total 13 km (AB 4 is rejected: it would make a cycle).

Route inspection (Chinese postman)

Find the shortest closed route that uses every edge at least once. If all degrees are even, the answer is the total weight. Otherwise pair up the odd-degree vertices and add the shortest paths between the pairs. In the 3D graph, B and E are odd; total weight 41 + shortest B–E path 7 = 48 km.

Travelling salesperson (TSP)

Find the shortest tour visiting every vertex once and returning. No fast exact method is known, so we find bounds:

The best tour lies between the two bounds.

Network flows: max flow and min cut

A flow network is a directed graph where each arc has a capacity (most it can carry), like pipes or roads. Flow leaves a source S and reaches a sink T. At every other vertex, flow in = flow out.

Example: S→A 4, S→B 3, A→B 2, A→T 3, B→T 4. Send 3 along S-A-T, 3 along S-B-T, 1 along S-A-B-T: flow 7. The cut {S} | {A, B, T} has capacity 4 + 3 = 7, so 7 is the maximum.

Try it: be the algorithm

Draw 6 dots for houses on your street and join them with lines; write distances in steps. Run Dijkstra by hand from your house using a table, then check with the free-play step (use start A). Then find the cheapest way to connect every house with cable (MST).

Key formulas and definitions

Worked examples

1. Run BFS from A on the 3D graph (neighbours in alphabetical order). Give the visit order.

Queue: A → take A, add B, C → take B, add D → take C, add E → take D, add F → take E → take F. Order: A, B, C, D, E, F. Layers: B, C at 1 edge; D, E at 2; F at 3.

2. Use Dijkstra from A to find the shortest route to F.

Fix A 0. Update B 4, C 2. Fix C 2; update B to 3 (via C), D 12, E 10. Fix B 3; D becomes 8. Fix D 8; E stays 10, F 14. Fix E 10; F becomes 13. Fix F 13. Route: A–C–B–D–E–F = 2 + 1 + 5 + 2 + 3 = 13 km.

3. Use Kruskal's algorithm to find the MST of the 3D graph.

Sorted: BC 1, AC 2, DE 2, EF 3, AB 4, BD 5, DF 6, CE 8, CD 10. Add BC, AC, DE, EF. AB makes cycle A-B-C: reject. Add BD. Now 5 edges for 6 vertices: done. Total = 1 + 2 + 2 + 3 + 5 = 13.

4. Give the pre-, in- and post-order traversals of the tree: root 8, left 3 (children 1 and 6), right 10.

Pre-order 8, 3, 1, 6, 10. In-order 1, 3, 6, 8, 10 (sorted, as it is a BST). Post-order 1, 6, 3, 10, 8.

5. Find the route inspection length for the 3D graph, starting and ending at A.

Degrees: A2, B3, C4, D4, E3, F2. Odd: B and E. Shortest B–E: B–D–E = 7 (B–C–E = 9). Total weight = 41. Route = 41 + 7 = 48 km; roads B–D and D–E are walked twice.

6. Network: S→A 4, S→B 3, A→B 2, A→T 3, B→T 4. Find the maximum flow and prove it.

Augment S-A-T by 3, S-B-T by 3, S-A-B-T by 1: flow = 7. Cut separating S from the rest has capacity 4 + 3 = 7. Flow = cut, so 7 is the maximum (max-flow min-cut).

Common mistakes

Practice quiz

1. Which data structure does BFS use?
2. In-order traversal of a binary search tree gives values:
3. Dijkstra's algorithm can fail when:
4. A spanning tree of a graph with 10 vertices has how many edges?
5. The max-flow min-cut theorem says the maximum flow equals:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is the difference between BFS and DFS?

BFS explores layer by layer with a queue; DFS goes deep down one path with a stack and backtracks.

How does Dijkstra's algorithm work in simple words?

Start at 0, then keep fixing the nearest town not yet fixed and updating its neighbours' distances, until every town is fixed.

What is the difference between Kruskal's and Prim's algorithm?

Both find a minimum spanning tree. Kruskal adds the cheapest edges anywhere that make no cycle; Prim grows one tree from a start vertex by its cheapest connecting edge.

Where this is taught

RomaniaClasa a XI-aGraphs
Ukraine11 класAlgorithms
England (GCSE, A level)Year 12Optional application 3 Discrete (part 1)
England (GCSE, A level)Year 134.3 Fundamentals of algorithms
England (GCSE, A level)Year 13Optional application 3 Discrete (part 2)
Germany (Bavaria)Jahrgangsstufe 11Graphs

Learn first

Learn next

Related lessons

All Computer Science lessons