progress

~/problems / Graphs / BFS / multi-source BFS

Shortest hop counts from one node

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write bfs_distances(n, edges, source) -> list[int]. The graph is undirected and unweighted, with nodes 0 .. n-1 and edges a list of pairs (a, b). Return a list dist of length n where dist[v] is the fewest edges on a path from source to v, or -1 if v can't be reached. dist[source] is 0.

bfs_distances(6, [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)], 0)
# [0, 1, 1, 2, 3, -1]
An undirected graph where node 0 is the source, nodes 1 and 2 are one hop away, node 3 two hops, node 4 three hops, and node 5 is disconnected with distance -1.

Edges may repeat and self-loops may appear. Constraints: 1 <= n <= 10**5, up to 2 * 10**5 edges.

Show hint

use a collections.deque as a FIFO queue and set dist[v] the moment you first enqueue v; because BFS finishes each distance before starting the next, that first value is already the shortest.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc