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 ton) andm(edges). The nextmlines each contain two nodesa bthat 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: dandPath: a -> b -> cwith the nodes separated by->. Otherwise showNo path.
6 6
1 2
1 3
2 4
3 4
4 5
5 6
1 6
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