Dsa
Graphs Bfs
Medium
Shortest Path in Network
You are given a network of nodes where each node represents a computer, and each edge represents a direct connection between two computers with a distance in milliseconds. Your task is to find the shortest time needed to send a data packet from a source computer to a destination computer through the network. Write a program that takes the number of computers, the number of connections, and a list of connections with their corresponding distances as input, and outputs the shortest path length in milliseconds.
Input format:
The first line contains integers n and m (number of computers and number of connections).
The next m lines contain three integers each: source node, destination node, and distance time.
The last line contains two integers: the source and destination nodes.
Output format:
Output the shortest distance from source to destination. If the destination is unreachable, output -1.
Example:
Input:
4 5
0 1 10
0 2 5
1 2 2
1 3 1
2 3 9
0 3
Output:
8
Key concepts
graphsbfsshortest-pathweights
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