Input data format N (number of edges, 1 ≤ N ≤ 1000),
next N lines with a pair of numbers for vertices, two numbers representing the start and end stations.
Output data format Number of transfers.
If there are no paths between stations, output "No path found".
** Example 1**
Input data:
4
1 2
2 3
3 4
4 5
1 5
Output:
3
import heapq
def min_transfers(edges, start, end):
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u) # Make the graph undirected
dist = {}
pq = [(0, start)]
while pq:
transfers, vertex = heapq.heappop(pq)
if vertex not in dist:
dist[vertex] = transfers
if vertex == end:
return transfers
for neighbor in graph[vertex]:
heapq.heappush(pq, (transfers + 1, neighbor))
return "No path found"
# Example usage
edges = [
(1, 2),
(2, 3),
(3, 4),
(4, 5)
]
start = 1
end = 5
min_transfers = min_transfers(edges, start, end)
print(min_transfers) #
Why it turns out to be 4 and not 3. How to fix it?