BFS to find distances 30 Marks Write a program that performs BFS on each of a given set…
- User
BFS to find distances 30 Marks Write a program that performs BFS on each of a given set of digraphs starting at node 1 and prints the distance to the most distant node from 1 and reports the node with the highest index at that distance. Nodes that are not reachable from 1 have an undefined distance and should be ignored. Input format: described below under the heading, “Digraph input format”. Output format: For each input digraph, print out a line with the distance to the most distant node, then a space, then the highest index of a node at that distance. Ignore nodes that are not reachable from 1. For the example input shown below, the output would be 2 0 0 1
Digraph input format A sequence of one or more digraphs is taken from the standard input (eg sys.stdin). Each graph is represented by an adjacency list. The first line is an integer n indicating the order of the graph. This is followed by n white space separated lists of adjacencies for nodes labeled 0 to n - 1. The lists are sorted. The input will be terminated by a line consisting of one zero (0). This line should not be processed. The sample input below shows two digraphs, the first has node set {0, 1, 2, 3} and arc set {(0, 1),(0, 3),(1, 2),(1, 3),(2, 0)}, the second has node set {0, 1, 2} and arc set {(0, 1),(0, 2),(2, 1)}. 4 1 3 2 3 0 3 1 2 1 0
- Assistant
Here is a Python program that fulfills the given requirements:
python