← DiffPush

Shortest Path in an Undirected Graph with Unit Weights

Standard Bar Graphs · Shortest Path Problems O(N + M) · O(N + M)

The Uniform-Hop Relay Distances

A packet relay mesh links routers with identical one-tick links. From the master router, ops needs each router's minimum tick count — the hop distance across the mesh — with unreachable routers flagged -1. Because every link costs exactly one tick, a level-by-level wave is sufficient; no weighted machinery required.

Input: An integer N (vertices 0..N-1), the edge count M, an edge list edges, and the source vertex src.

Output: Return an array where entry i is the minimum hop count from src to vertex i, or -1 if unreachable.

Constraints

Examples

Example 1

Input: {"N":6,"M":5,"src":0,"edges":[[0,1],[0,3],[1,2],[3,4],[4,5]]}
Output: [0,1,2,1,2,3]
Wave rings: 0 first, 1 and 3 at one hop, 2 and 4 at two, 5 at three.

Example 2

Input: {"N":4,"M":2,"src":0,"edges":[[0,1],[2,3]]}
Output: [0,1,-1,-1]
Vertices 2 and 3 live on an island the wave never crosses.

Solve this in your browser →

Also on LeetCode ↗