Shortest paths and spanning trees
A weighted graph and a question: what is the cheapest path from one vertex to another? Here you see Dijkstra step by step with the same table the exam asks for («cost,vertex», «-» for what is not reached yet and «*» for closed vertices), you can fill in your own table and check it cell by cell, and you see how Kruskal and Prim build the minimum spanning tree. It runs in your browser, on your phone too.
How to use it
- Start with «From home to campus»: seven stops in Gran Canaria, from Escaleritas to the Tafira campus, and Dijkstra column by column until you see why the route with more stops comes out cheaper.
- Go on with «The exam table», shaped like the classroom problems, and with «Kruskal: just what is needed» and «Prim: growing from home» on the bus graph.
- In «Your graph» type the edges as
a b 7, one per line, choose the algorithm, the start and the end vertex, and drag the vertices to tidy up the drawing. - Press «Fill in my table», copy the one you did on paper and press «Check my table»: the cells that do not match are marked and you can see the right one.
What it works out
With Dijkstra, at each step it closes the open vertex with the lowest cost and looks at its neighbours: if getting there through it is cheaper, it changes their cell to the new «cost,vertex»; if not, it leaves it as it was. At the end it rebuilds the path by walking back through the vertices in the cells. With Kruskal it sorts the edges by weight and adds each one unless it closes a cycle; with Prim it grows the tree from one vertex, each time adding the cheapest edge leaving it. Both give the same total weight.
The rules it follows
- If two open vertices tie on cost, it closes the one that comes first alphabetically.
- A cell only changes if the new cost is strictly lower; on a tie the vertex already there stays.
- Weights must be positive: with negative weights Dijkstra can get it wrong.
For the exam
The exam asks for the whole table, with one column per step and the «*» on the vertices already closed, and the path and its cost at the end. Filling in the table here before looking at it is the best way to see where you go wrong. The challenge below asks for new shortest-path costs, table cells and spanning tree weights every time.
