Asked inJPMorgan Chase & Co.,Quantitative Research
Shortest path in an unweighted graph

The city of Ninjaland is analogous to the unweighted graph. The city has ‘N’ houses numbered from 1 to ‘N’ respectively and are connected by M bidirectional roads. If a road is connecting two houses ‘X’ and ‘Y’ which means you can go from ‘X’ to ‘Y’ or ‘Y’ to ‘X’. It is guaranteed that you can reach any house from any other house via some combination of roads. Two houses are directly connected by at max one road.

A path between house ‘S’ to house ‘T’ is defined as a sequence of vertices from ‘S’ to ‘T’. Where starting house is ‘S’ and the ending house is ‘T’ and there is a road connecting two consecutive houses. Basically, the path looks like this: (S , h1 , h2 , h3 , ... T). you have to find the shortest path from ‘S’ to ‘T’.

For example
In the below map of Ninjaland let say you want to go from S=1 to T=8, the shortest path is (1, 3, 8). You can also go from S=1 to T=8  via (1, 2, 5, 8)  or (1, 4, 6, 7, 8) but these paths are not shortest.

altImage

Input Format :
The first line of input will have a single positive integer ‘T’, denoting the number of test cases. 

The first line of each test case has two positive integers ‘N’ and ‘M’ denoting the number of houses and the number of roads in the ninja land.

The second line contains two integers ‘S’ and ‘T’ denoting the starting and ending house in the path.

Next M lines each contain two integers ‘X’ and ‘Y’. Which denotes a road between house ‘X’ and house ‘Y’.   
Output Format :
You have to return a vector of nodes denoting the shortest path starting from ‘S’ and ending in ‘T’.

If there is more than one shortest path you can return any one of them.

The output of each test case will be "Correct" if you have returned the correct answer, else it will be "Incorrect".

Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function. 
Constraints :
1 <= T <= 100
2 <= N <= 10 ^ 3
1 <= M <= min( N *(N - 1) / 2 , 1000 )
1 <= S, T <= N

Time Limit: 1 sec
CodingNinjas
author
2y

Used Floyd Warshall algorithm.

CodingNinjas
author
2y
BFS
  • Store all the edges in the form of an adjacency list ADJ. if ADJ[X][j] = Y which means there is an edge from X to Y.
  • Declare a queue Q and push S in it and also declare two vectors VISITED and DISTA...read more
Help your peers!
Add answer anonymously...
JPMorgan Chase & Co. Quantitative Research Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter