Facebook Pixel

Shortest Path Between A and B

Prereq: BFS on Graph

Given an (unweighted) connected graph, return the length of the shortest path between two nodes A and B, in terms of the number of edges.

Assume there always exists a path between nodes A and B.

Input:

graph = [[1, 2], [0, 2, 3], [0, 1], [1]]
A = 0
B = 3

Output: 2

Note that the graph input is an adjacency list representation, not an adjacency matrix or a 2D grid. Specifically, graph[i] is the list of neighbor nodes for node i. For example, graph = [[1, 2], [0], [0]] means node 0 has edges to nodes 1 and 2. You can use the BFS template from BFS on Graphs as your starter code.

Try it yourself

Explanation

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro