Part 16 / Topic 11 of 12
Graphs: adjacency list, BFS and DFS
A graph is just nodes (vertices) and connections (edges). The adjacency list — a map from each node to the list of nodes it connects to — is the representation to reach for almost every time; an adjacency matrix (an n × n grid of 0s/1s) only earns its place when the graph is dense or you need O(1) "are these two directly connected?" checks on a small, fixed set of nodes.
| BFS (breadth-first) | DFS (depth-first) | |
|---|---|---|
| Data structure | queue | stack (or recursion) |
| Explores | level by level, outward | one path, as deep as possible, then backtracks |
| Finds | the shortest path by hop count | any path; good for "does a path exist," cycle checks |
List<String> bfs(String start) {
List<String> order = new ArrayList<>();
Set<String> visited = new HashSet<>();
Deque<String> queue = new ArrayDeque<>();
queue.offer(start); visited.add(start);
while (!queue.isEmpty()) {
String node = queue.poll();
order.add(node);
for (String neighbor : neighborsOf(node)) {
if (visited.add(neighbor)) queue.offer(neighbor); // add() is false if already present
}
}
return order;
}
$ javac GraphDemo.java
$ java GraphDemo
-- BFS from Dadar (level by level) --
[Dadar, Parel, Matunga, Lower Parel, Sion, Mahalaxmi, Kurla, Ghatkopar]
-- DFS from Dadar (as deep as possible first) --
[Dadar, Parel, Lower Parel, Mahalaxmi, Matunga, Sion, Kurla, Ghatkopar]
-- shortest path, Mahalaxmi to Ghatkopar --
[Mahalaxmi, Lower Parel, Parel, Dadar, Matunga, Sion, Kurla, Ghatkopar]
-- cycle detection: a tree-shaped network has none --
has cycle: false
A-B-C-A has cycle: true
BFS and DFS visit the same nodes but in a genuinely different order, because one uses a queue (FIFO: finish this level before starting the next) and the other a stack (LIFO: keep going deeper before coming back) — the exact same swap that turned GraphDemo's traversal into the delivery-route planner's Dijkstra below, just with a plain queue swapped for a priority queue instead of a stack.
Full program: examples/graphs/GraphDemo.java.
Real-world build 3: a delivery route planner
Plain BFS finds the path with the fewest roads (hops) — the wrong question the moment roads take different amounts of time. Dijkstra's algorithm is BFS with its queue swapped for a PriorityQueue ordered by travel time, so the next stop explored is always the one with the smallest known travel time so far, not just the next one in line.
PriorityQueue<Edge> frontier = new PriorityQueue<>(Comparator.comparingInt(Edge::minutes));
best.put(start, 0);
frontier.offer(new Edge(start, 0));
while (!frontier.isEmpty()) {
Edge current = frontier.poll();
int knownTime = best.get(current.to());
if (current.minutes() > knownTime) continue; // a cheaper way here was already processed
for (Edge road : adjacency.getOrDefault(current.to(), List.of())) {
int candidate = knownTime + road.minutes();
if (candidate < best.getOrDefault(road.to(), Integer.MAX_VALUE)) {
best.put(road.to(), candidate);
cameFrom.put(road.to(), current.to());
frontier.offer(new Edge(road.to(), candidate));
}
}
}
$ javac DeliveryRouteDemo.java
$ java DeliveryRouteDemo
-- fastest delivery time from the Warehouse to every stop (Dijkstra) --
Kothrud 12 min
Baner 9 min
Aundh 15 min
Shivaji Nagar 23 min
Camp 31 min
-- the actual route for the longest leg, Warehouse to Camp --
Warehouse -> Kothrud -> Shivaji Nagar -> Camp (31 min total)
-- why not just BFS (fewest ROADS, ignoring minutes)? --
Warehouse -> Aundh direct road: 1 hop but would show as the 'shortest' under BFS
Warehouse -> Baner -> Aundh: 2 hops, but only 15 min -- faster, and Dijkstra finds it
There's a direct, one-hop road from the Warehouse to Aundh — 20 minutes, slow and congested — and a two-hop road through Baner that only takes 15. BFS, counting hops, would wrongly prefer the direct road; Dijkstra, accumulating actual minutes with a PriorityQueue, correctly prefers the longer-looking route that's actually faster. The if (current.minutes() > knownTime) continue; line matters: a node can be added to the frontier more than once (once per road that reaches it), and only the entry matching the current best known time should actually be processed — anything stale is skipped.
Full program: examples/graphs/DeliveryRouteDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.