Skip to content

4.3 Find a shortest path between two nodes

You get the distance from a node to every other node, and a path with the fewest edges.

How do you get from one node to another along as few edges as possible? Each edge counts as one step. The number of edges on a shortest path is called the distance. Such questions come up for:

  • the shortest chain of calls from the entry point of a program to a method, which explains how the method is reached;
  • the fewest connections between two machines of a network;
  • the fewest moves between two states of a game or a puzzle.

The example graph calls models the calls between the methods of a small program. It has an edge from each method to each method it calls. How many calls away from main is write, and along which chain of calls? The picture after shows in green the methods on a shortest path from the start node main to write.

The calls, the start node and the methods asked about
The methods on a shortest path from main to write
0: main1: parseArgs2: run3: load4: save5: show6: parse7: format8: read9: write
0: main1: parseArgs2: run3: load4: save5: show6: parse7: format8: read9: write
Input
  • Start node or method asked about
Output
  • Method on the path

BfsDistances.ofBfsDistances::ofBfsDistances.ofBfsDistances.Of searches from main and keeps the distance of every node it reaches:

BfsDistances fromMain = BfsDistances.of(calls, main);
int distance = fromMain.distanceOf(write); // 3 - three calls away
// [0, 2, 4, 9] - main, run, save, write
IntList path = fromMain.pathTo(write);
boolean reached = fromMain.isReachable(parseArgs); // true
Full example
let from_main = BfsDistances::of(&calls, main);
let distance = from_main.distance_of(write); // Some(3) - three calls away
let path = from_main.path_to(write); // [0, 2, 4, 9] - main, run, save, write
let reached = from_main.is_reachable(parse_args); // true
Full example
const fromMain = BfsDistances.of(calls, main);
const distance = fromMain.distanceOf(write); // 3 - three calls away
// [0, 2, 4, 9] - main, run, save, write
const path = fromMain.pathTo(write);
const reached = fromMain.isReachable(parseArgs); // true
Full example
BfsDistances fromMain = BfsDistances.Of(calls, main);
int distance = fromMain.DistanceOf(write); // 3 - three calls away
// [0, 2, 4, 9] - main, run, save, write
ImmutableArray<int> path = fromMain.PathTo(write);
bool reached = fromMain.IsReachable(parseArgs); // true
Full example

write is three calls away. BfsDistances.pathToBfsDistances::path_toBfsDistances.pathToBfsDistances.PathTo lists the nodes of the path from the start node to write. They are the green methods of the picture after: main calls run, run calls save and save calls write. BfsDistances.isReachableBfsDistances::is_reachableBfsDistances.isReachableBfsDistances.IsReachable tells whether the search reaches a node at all. It reaches parseArgs.