Find the shortest distance from a source to every reachable vertex in an unweighted graph using breadth-first search in Java and Python.
Problem and input contract
Provide an adjacency map from string vertex IDs to lists of outgoing neighbors and a non-null starting ID. Use both directions for undirected edges. A missing key means the vertex has no outgoing edges. The result maps each reachable vertex to its minimum edge count.
For A → B, C and B → D, with C → D, the distances are A: 0, B: 1, C: 1, D: 2. An isolated A returns only A: 0. With A → A, B, the self-loop leaves A at 0 and B is 1 away.
Worked example
If A links to B and C, and B links to D, the distance from A to D is 2.
Queue A with distance 0. Processing A discovers B and C at distance 1. When B is removed, discover D at distance 2. If C also points to D, skip it because D already has a shortest distance.
How the solution works
The queue visits vertices in layers. The first discovery gives the fewest edges. Marking a vertex when enqueued prevents cycles from adding it repeatedly.
Process the queue in arrival order and mark each vertex when it enters. For a weighted graph, a path with fewer edges can have a higher total cost, so this approach is for unweighted distances.
Python solution
from collections import deque
def shortest_distances(graph, start):
distance = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph.get(node, ()):
if neighbor not in distance:
distance[neighbor] = distance[node] + 1
queue.append(neighbor)
return distanceJava solution
import java.util.*;
class Solution {
static Map<String, Integer> shortestDistances(Map<String, List<String>> graph, String start) {
Map<String, Integer> distance = new HashMap<>();
Queue<String> queue = new ArrayDeque<>();
distance.put(start, 0);
queue.add(start);
while (!queue.isEmpty()) {
String node = queue.remove();
for (String next : graph.getOrDefault(node, Collections.emptyList())) {
if (!distance.containsKey(next)) {
distance.put(next, distance.get(node) + 1);
queue.add(next);
}
}
}
return distance;
}
}Approaches and complexity
Repeated edge relaxation can find distances by rescanning the graph. BFS instead processes each reachable vertex once and scans its outgoing edges once, taking O(V + E) time with expected constant-time hash operations. The output map holds O(V) entries and the queue can hold O(V) additional entries.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Repeated relaxation | O(VE) | O(V) | Simple edge-based reasoning | Rescans edges | Reference checks |
| BFS | O(V + E) | O(V) | Finds distances layer by layer | Requires equal edge costs | Unweighted shortest paths |
Common mistakes and interview follow-up
Mark a neighbor when you enqueue it to avoid duplicate queue entries. To recover paths, record each vertex’s predecessor at discovery and follow those references backward from the destination.
Related practice: Find children of a given binary tree by target node or by target value.
Comments
Post a Comment