Data structures · 13 / 15 Exercise Hard

Shortest path in a graph

Objective

Create a Python program that finds the shortest path (fewest edges) between two nodes of an undirected graph using a breadth-first search (BFS) with a queue.

Instructions

  • The first line contains n m (nodes, numbered from 1 to n) and m (edges). The next m lines each contain two nodes a b that are connected (in both directions). The last line contains the source and the target node.
  • Store the graph in a dictionary of neighbor lists. In the BFS visit the neighbors of each node in increasing order and show the first path it finds.
  • If there is a path, show Distance: d and Path: a -> b -> c with the nodes separated by -> . Otherwise show No path.
Input
6 6
1 2
1 3
2 4
3 4
4 5
5 6
1 6
Output
Distance: 4
Path: 1 -> 2 -> 4 -> 5 -> 6

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise