Skip to content
DeepForgeby svx
All problems
MediumGraph Algorithmsgraph-020

BFS Shortest Path Unweighted

Problem

Return the number of edges in a shortest path between src and dst in an undirected unweighted graph with n nodes.

If dst is unreachable, return -1; if src equals dst, return 0. edges is a list of [u, v] pairs.

Hint

First time a node is dequeued its distance is final in BFS.

Test cases

case 1
in: [6,[[0,1],[0,2],[1,3],[2,3],[3,4],[4,5]],0,5]
expected: 4
case 2
in: [6,[[0,1],[0,2],[1,3],[2,3],[3,4],[4,5]],1,2]
expected: 2
case 3
in: [3,[[0,1]],0,2]
expected: -1
case 4
in: [2,[],1,1]
expected: 0
Starter codePython
def bfs_shortest_path(n, edges, src, dst):
    # Your code here
    pass

4 test cases · run your code against them in the editor