Update appNew update is available. Click here to update.

Get Path using BFS

Last Updated: 22 Jul, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given an undirected graph G(V, E), where ‘V’ is the number of vertices and ‘E’ is the number of edges present in the graph and two integers ‘v1’ and ‘v2’ denoting vertices of the graph, find and print the path from ‘v1’ to ‘v2’ (if exists) in reverse order. Print an empty list if there is no path between ‘v1’ and ‘v2’.

Find the path using BFS and print the first path that you encountered.

Note:
Vertices are numbered through 0 to V - 1.
Input Format :
The first line contains a single integer ‘T’ denoting the number of test cases. Then each testcase follow.

The first line of each test case contains two integers ‘V’ and ‘E’ denoting the number of vertices and edges in the graph.

The next ‘E’ lines of the test case contain two space-separated integers ‘a’ and ‘b’ denoting that there exists an edge between ‘a’ and ‘b’.

The last line of the test case contains two space-separated integers ‘v1’ and ‘v2’ denoting the starting vertex and ending vertex.
Output Format :
For each test case, print the path from ‘v1’ to ‘v2’ in reverse order.

Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function and return a list of paths.

If there is no path between the vertices return an empty list.If the path is valid then it will print true else it will print false.
Constraints :
1 <= T <= 10
1 <= V <= 1000
1 <= E <= (V * (V - 1)) / 2
0 <= v1, v2 <= V-1


Time Limit: 1sec