oneby7

Graphs Fewest steps with BFS

447. Shortest Path with Unit Weights

Medium

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

0src12345

Input: n = 6 edges = [[0, 1], [2, 1], [2, 5], [3, 0], [5, 3], [4, 5]] src = 0

Output: [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

0123src4

Input: n = 5, edges = [[1, 2], [2, 3]], src = 3

Output: [-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

0src

Input: n = 1, edges = [], src = 0

Output: [0]

Check your understanding

Work out the answer for this input before you write any code.

n = 5 edges = [[1, 0], [1, 2], [3, 2], [0, 3]] src = 0

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.