Given an undirected graph with V vertices (0 .. V-1) and edge list edges where every edge has weight 1, return an array dist with the shortest distance from source vertex 0 to every vertex (the fewest edges), or -1 if unreachable.
Input: V = 5, edges = [[0,1],[0,2],[1,3],[3,4]] Output: [0, 1, 1, 2, 3] BFS levels from vertex 0.
Input: V = 4, edges = [[0,1],[2,3]] Output: [0, 1, -1, -1] Vertices 2 and 3 aren't reachable from 0.
- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - all edges have weight 1 - no self-loops or duplicate edges
When every edge costs the same, BFS is the shortest-path algorithm: it visits vertices in order of increasing distance, so the level at which a vertex is first reached is its shortest distance. Start a BFS from source 0 with dist[0] = 0; each unvisited neighbour gets dist[u] + 1. Unreached vertices keep -1. O(V + E) — no priority queue, because with unit weights BFS's queue already dequeues in distance order.
(The brute alternative — Bellman-Ford-style relaxation of all edges V-1 times — gives the same answer at O(V·E), but is overkill when a plain BFS suffices.)
“All edge weights equal?”
Yes — weight 1, so BFS applies.
“Source and unreachable?”
Source is 0; unreachable vertices report -1.
With unit weights, BFS from the source gives shortest distances — the level a vertex is first reached at.
It's O(V+E); no heap needed because the queue already processes vertices in distance order.
Worked example — V = 5, edges [[0,1],[0,2],[1,3],[3,4]]
level 0: 0 level 1: 1, 2 level 2: 3 level 3: 4 dist = [0, 1, 1, 2, 3]
Unit weights make ring number equal shortest distance.
Mark distance when a vertex is first dequeued-neighbour.
The queue already yields vertices in distance order.
| Edge relaxation | BFS | |
|---|---|---|
| Idea | relax all edges V-1 times | expand rings from the source |
| Time | O(V·E) | O(V+E) |
| Needs unit weights |
Both give the same distances; BFS is the right tool for unit weights. Full code is in the Approaches selector below.
Key takeaway
With unit weights, BFS from the source computes all shortest distances in O(V+E): the level a vertex is first reached is its distance. Unreached ⇒ -1.
dist[0]=0; BFS; neighbour's dist = dist[u]+1 on first visit