Stop 10 · Data Structures & Algorithms in JavaTopics · 10/11

Graphs (BFS & DFS)

Part of the Java Roadmap

In short

Road maps, metro lines, friend suggestions and course prerequisites are all graphs. With BFS and DFS you can find shortest routes, connected groups and cycles in any of them.

Graphs model connections like networks and maps. BFS explores level by level with a queue and finds shortest paths in unweighted graphs, while DFS explores deeply with recursion or a stack.

The jaadu stands at a railway junction holding a lantern, with track branches spreading out like ripples in every direction.

Think of it like this

The Mumbai local map

To find the fewest stops from Andheri to CST, you check every station one stop away, then every station two stops away, and so on. The first time you reach CST is the shortest route. That ripple is BFS. Walking one line to its very end before trying another is DFS.

Watch it happen

BFS queue from Andheri

enqueue(Andheri)
Andheri

Front of the queue is coloured

1/9Start at Andheri, distance 0.

The big ideas

What you need to know

Adjacency list

Store a graph as Map<Node, List<Node>> or List<List<Integer>>. It uses memory proportional to edges, unlike a full matrix.

BFS uses a queue

It explores level by level, so it finds the fewest-edges path in an unweighted graph.

DFS goes deep

Using recursion or a stack, it explores one path fully before backing up. Good for connected components and cycle checks.

Track visited

Graphs can have cycles. Without a visited set, BFS and DFS loop forever. Both run in O(V + E).

See it in code

Walk through the code

java
1import java.util.*;2 3public class GraphDemo {4    static Map<String, List<String>> graph = new HashMap<>();5 6    static void addEdge(String a, String b) {7        graph.computeIfAbsent(a, k -> new ArrayList<>()).add(b);8        graph.computeIfAbsent(b, k -> new ArrayList<>()).add(a);9    }10 11    // BFS: fewest hops from start to every reachable station12    static Map<String, Integer> bfs(String start) {13        Map<String, Integer> dist = new HashMap<>();14        Deque<String> queue = new ArrayDeque<>();15        dist.put(start, 0);16        queue.offer(start);17        while (!queue.isEmpty()) {18            String cur = queue.poll();19            for (String next : graph.getOrDefault(cur, List.of())) {20                if (!dist.containsKey(next)) {       // first visit is the shortest21                    dist.put(next, dist.get(cur) + 1);22                    queue.offer(next);23                }24            }25        }26        return dist;27    }28 29    // DFS: visit everything reachable, going deep first30    static void dfs(String cur, Set<String> visited) {31        if (!visited.add(cur)) return;32        for (String next : graph.getOrDefault(cur, List.of())) dfs(next, visited);33    }34 35    public static void main(String[] args) {36        addEdge("Andheri", "Bandra");37        addEdge("Bandra", "Dadar");38        addEdge("Andheri", "Ghatkopar");39        addEdge("Ghatkopar", "Dadar");40        addEdge("Dadar", "CST");41        System.out.println(bfs("Andheri").get("CST"));  // 342        Set<String> seen = new HashSet<>();43        dfs("Andheri", seen);44        System.out.println(seen.size());                // 545    }46}

1/4Undirected edge: add each station to the other's neighbour list.

An undirected station graph with BFS for shortest hops and DFS for reachability.

Save yourself the pain

Common mistakes

Oops

Marking a node visited when you take it out of the queue.

Do this instead

Mark it when you add it. Otherwise the same node can be queued many times.

Oops

Using BFS for shortest paths when edges have different weights, like travel times.

Do this instead

BFS counts hops only. Use Dijkstra's algorithm with a PriorityQueue for weighted edges.

Oops

Running DFS only from node 0 to count components.

Do this instead

Loop over every node and start a new DFS from each unvisited one.

Your mission

Graph basics

~75 min

Quick check

Why does BFS find the shortest path in an unweighted graph?

Go deeper

  1. 1Represent a graph with an adjacency list using List<List<Integer>>.
  2. 2Implement BFS and DFS and count connected components.
  3. 3Solve 'number of islands' on a grid.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge