Graphs Fewest steps with BFS
447. Shortest Path with Unit Weights
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in
edges is an edge between vertices u and v, and it can be used in both directions. Every edge has length 1.
You are also given a starting vertex src. Return an array of length n whose entry v is the fewest edges
on any path from src to vertex v. The entry for src itself is 0. If no path leads from src to a
vertex, its entry is -1.
Example 1
Input: n = 6
edges = [[0, 1],
[2, 1],
[2, 5],
[3, 0],
[5, 3],
[4, 5]]
src = 0
[0,1,2,1,3,2]Explanation: Vertices 1 and 3 are one edge from vertex 0. Vertex 5 is two edges away through vertex 3, although the path through 1 and 2 takes three. Vertex 4 is one edge past vertex 5.
Example 2
Input: n = 5, edges = [[1, 2], [2, 3]], src = 3
[-1,2,1,0,-1]Explanation: Vertex 2 is one edge from vertex 3, and vertex 1 is two. No path leads from vertex 3 to vertex 0 or vertex 4, so their entries are -1.
Example 3
Input: n = 1, edges = [], src = 0
[0]Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice:
[u, v]and[v, u]are the same edge. 0 ≤ src < n
Clarifying questions
What you would ask an interviewer before writing any code.