Skip to main content

Unweighted Shortest Paths with BFS in Java and Python

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 distance

Java 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 comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
Repeated relaxationO(VE)O(V)Simple edge-based reasoningRescans edgesReference checks
BFSO(V + E)O(V)Finds distances layer by layerRequires equal edge costsUnweighted 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

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...