Codele / Algorithms
Shortest paths
Roads have different lengths, so the fewest turns is not always the shortest drive. Always settle the closest town next, and the shortest distances appear one by one.
- Roads have weights (lengths). The shortest route is the smallest total length, not the fewest roads.
- Keep a best-known distance for every town: “?” (far away) at first, 0 for the start. The code uses 99 for far away.
- Always settle the closest unsettled town next. Its distance is then final, because any other way would go through a farther town first.
- After settling a town, try each road from it: if it gives a shorter way to a neighbour, update that neighbour and remember where it came from.
- This is Dijkstra’s algorithm. Picking the closest town with a plain loop is slow for big maps; a smarter helper called a priority queue makes that step fast.
Loading the playable lesson…