Part 17 / 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 |
fun bfs(start: String): List<String> {
val order = mutableListOf<String>()
val visited = hashSetOf(start)
val queue = ArrayDeque<String>()
queue.addLast(start)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
order.add(node)
for (neighbor in neighborsOf(node)) {
if (visited.add(neighbor)) queue.addLast(neighbor) // add() is false if already present
}
}
return order
}
$ kotlinc GraphDemo.kt -include-runtime -d graph.jar
$ java -jar graph.jar
-- 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 turns 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.kt.
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.
val frontier = PriorityQueue<Road>(compareBy { it.minutes })
best[start] = 0
frontier.offer(Road(start, 0))
while (frontier.isNotEmpty()) {
val current = frontier.poll()
val knownTime = best.getValue(current.to)
if (current.minutes > knownTime) continue // a cheaper way here was already processed
for (road in roadsFrom(current.to)) {
val candidate = knownTime + road.minutes
if (candidate < (best[road.to] ?: Int.MAX_VALUE)) {
best[road.to] = candidate
cameFrom[road.to] = current.to
frontier.offer(Road(road.to, candidate))
}
}
}
$ kotlinc DeliveryRouteDemo.kt -include-runtime -d delivery.jar
$ java -jar delivery.jar
-- 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.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.