Dsa
Graphs Bfs
Easy
Metro Connectivity
You are given a map of a city's metro system as an undirected graph. Each station is a node and each line connecting two stations is an edge. Write a program to find the shortest path in terms of number of lines taken to get from a starting station to a destination station. You will receive the number of stations, followed by a list of lines as pairs representing the connections between the stations, and finally a pair of stations indicating the start and end. If there is no path, return -1.
Input Format:
- The first line contains an integer n (number of stations).
- The second line contains an integer m (number of connections).
- The next m lines contain two integers u and v, representing a connection between stations u and v.
- The last line contains two integers s and d, the start station and the destination station.
Output Format:
- Print the minimum number of lines needed to reach the destination station from the start station, or -1 if no such path exists.
Example:
Input:
5
4
1 2
1 3
2 4
3 4
1 4
Output:
2
Key concepts
bfsgraphshortest-path
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now