Graph BFS Shortest Path Unweighted (Java)

Find the shortest path in an unweighted Java graph using BFS with a predecessor map for path reconstruction.

JavaData Fetching

Code

javasnippet
19 lines
import java.util.*;
public class BFS {
    public static List<String> shortestPath(Map<String, List<String>> graph, String start, String end) {
        if (start.equals(end)) return List.of(start);
        Deque<String> queue = new ArrayDeque<>(List.of(start));
        Set<String> visited = new HashSet<>(List.of(start));
        Map<String, String> parent = new HashMap<>();
        while (!queue.isEmpty()) {
            String node = queue.poll();
            for (String neighbor : graph.getOrDefault(node, List.of())) {
                if (visited.contains(neighbor)) continue;
                visited.add(neighbor); parent.put(neighbor, node);
                if (neighbor.equals(end)) { List<String> path = new ArrayList<>(List.of(end)); String cur = end; while (parent.containsKey(cur)) { cur = parent.get(cur); path.add(0, cur); } return path; }
                queue.add(neighbor);
            }
        }
        return null;
    }
}

Inside the snippet

Count the class BFS and the function shortestPath as the entire surface area of Graph BFS Shortest Path Unweighted (Java).

Repetition is confined to while (!queue.isEmpty()) — the rest of the file is straight-line.

Using it

The main signature reads public static List<String> shortestPath(Map<String, List<String>> graph, String start, String end)

Key statements

if (start.equals(end)) return List.of(start);

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `shortestPath` at load time.