Shortest path in undirected graph with unit weights
Pattern: Shortest paths
When every edge costs 1, BFS from the source visits vertices in order of distance, so the first time a vertex is reached is its shortest distance.
The problem
Given an undirected graph where every edge has length 1 and a source vertex, return the shortest distance to every vertex,
or -1 if it cannot be reached. Vertices are numbered from 0 and each edge is given as [u, v].
Think first
- Which search visits vertices in order of distance?
- When is a vertex's distance known?
- Why not Dijkstra?
Hints
Brute force, and why it fails
Dijkstra: O(E log V).
The key insight
With equal weights, the BFS queue is already sorted by distance.
Dry run
| dist | 0 1 - 1 |
|---|
Source 0 in the 9-vertex example. Distance 1: 1 and 3.
Step 1 of 3
The plan
dist = -1; dist[src] = 0; BFS: unvisited neighbour gets dist + 1
Complexity
- Time
O(V + E)- Space
O(V)
Each vertex and edge once.
Edge cases
- A single vertex with no edges.
- A graph in several pieces.
- The source alone: [0].
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> shortestPathUnit(int n, int[][] edges, int src) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[src] = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(src);
while (!q.isEmpty()) { // with equal weights, BFS order is distance order
int u = q.poll();
for (int v : adj.get(u)) if (dist[v] == -1) { dist[v] = dist[u] + 1; q.add(v); }
}
List<Integer> out = new ArrayList<>();
for (int d : dist) out.add(d);
return out;
}
}C++
class Solution {
public:
vector<int> shortestPathUnit(int n, vector<vector<int>>& edges, int src) {
vector<vector<int>> adj(n);
for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
vector<int> dist(n, -1);
dist[src] = 0;
queue<int> q;
q.push(src);
while (!q.empty()) { // with equal weights, BFS order is distance order
int u = q.front();
q.pop();
for (int v : adj[u]) if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
}
return dist;
}
};Python
from collections import deque
class Solution:
def shortestPathUnit(self, n: int, edges: list[list[int]], src: int) -> list[int]:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
dist = [-1] * n
dist[src] = 0
q = deque([src])
while q: # with equal weights, BFS order is distance order
u = q.popleft()
for v in adj[u]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
return distCommon mistakes
- Using DFS.
- Setting the distance when a vertex leaves the queue.