Practice: advanced graphs
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Synthesize advanced graph algorithms to select the optimal technique based on problem structure and constraints.
Algorithm selection from problem constraints
Hard graph problems require selecting the exact algorithm matching input limits. If edge weights are negative or paths have hop limits, use Bellman-Ford in O(V * E) time. If all-pairs shortest paths are queried and V <= 400, Floyd-Warshall in O(V^3) time is unbeatable.
Example 1 · City with Smallest Neighbours at Threshold
import java.util.Arrays;
public class CityNeighborsPracticeDemo { public static final int INF = 1_000_000_000;
public static int findTheCity(int n, int[][] edges, int distanceThreshold) { int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], INF); dist[i][i] = 0; } for (int[] e : edges) { dist[e[0]][e[1]] = e[2]; dist[e[1]][e[0]] = e[2]; }
for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] != INF && dist[k][j] != INF) { dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } }
int minCount = n + 1; int bestCity = -1; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (i != j && dist[i][j] <= distanceThreshold) count++; } if (count <= minCount) { minCount = count; bestCity = i; // Tie break with larger index } } return bestCity; }
public static void main(String[] args) { int n = 4; int[][] edges = {{0, 1, 3}, {1, 2, 1}, {2, 3, 4}, {0, 3, 2}}; int city = findTheCity(n, edges, 4); System.out.println("Best city index: " + city); }}Best city index: 3
What this code does
- Computes all-pairs shortest paths using Floyd-Warshall in O(V^3) time.
- Counts cities reachable within threshold 4 for each candidate node.
- Selects city 3 having fewest reachable neighbours.
When a directed graph is acyclic, topological sort relaxation finds shortest and longest paths in linear O(V + E) time. If configurations transition discrete states with uniform moves, deploy state space BFS with bitmasks. To partition directed networks into mutually reachable groups, Kosaraju and Tarjan extract SCCs in O(V + E) time. To identify single points of failure in undirected networks, Tarjan finds bridges and cut vertices. To traverse every edge exactly once, Hierholzer reconstructs Eulerian paths. To solve assignment or bottleneck capacity challenges, Edmonds-Karp maximum flow provides polynomial solutions.
Pattern walkthrough: Cheapest flights within k stops
Dijkstra fails on bounded stops because a cheaper path might exceed the layover limit. Bellman-Ford cleanly solves this constraint when restricted to exactly k + 1 iterations. Each iteration corresponds to paths containing exactly one more flight segment.
Example 2 · Cheapest Flights Within K Stops
import java.util.Arrays;
public class CheapestFlightsPracticeDemo { public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { int INF = 1_000_000_000; int[] dist = new int[n]; Arrays.fill(dist, INF); dist[src] = 0;
for (int i = 0; i <= k; i++) { int[] temp = Arrays.copyOf(dist, n); for (int[] flight : flights) { int u = flight[0]; int v = flight[1]; int price = flight[2]; if (dist[u] != INF && dist[u] + price < temp[v]) { temp[v] = dist[u] + price; } } dist = temp; } return dist[dst] == INF ? -1 : dist[dst]; }
public static void main(String[] args) { int n = 4; int[][] flights = {{0, 1, 100}, {1, 2, 100}, {2, 3, 100}, {0, 2, 500}}; int res1 = findCheapestPrice(n, flights, 0, 3, 1); int res2 = findCheapestPrice(n, flights, 0, 3, 2); System.out.println("Cost within 1 stop: " + res1); System.out.println("Cost within 2 stops: " + res2); }}Cost within 1 stop: 600 Cost within 2 stops: 300
What this code does
- Restricts edge relaxation passes to exactly k + 1 iterations.
- Finds cost 600 within 1 stop via path 0 -> 2 -> 3.
- Finds cost 300 when allowing 2 stops via path 0 -> 1 -> 2 -> 3.
Before relaxing edges in round i, make an exact copy of the previous distance array. When relaxing edge u->v with price w, read from the copied array and write into the working array. This copy prevents cascading multiple flights within a single iteration. If dist[dst] remains infinity after k + 1 rounds, return -1 indicating unreachable destination.
Pattern walkthrough: Critical connections in a network
A bridge is an edge whose removal splits an undirected graph, like a critical cable whose failure partitions a computer network. Tarjan's algorithm runs depth-first search while maintaining discovery times tin and low-link values low.
void dfs(int u, int parent) { tin[u] = low[u] = timer++; for (int v : adj.get(u)) { if (v == parent) continue; // skip the edge back to the parent if (tin[v] != -1) { low[u] = Math.min(low[u], tin[v]); // back edge } else { dfs(v, u); low[u] = Math.min(low[u], low[v]); if (low[v] > tin[u]) bridges.add(List.of(u, v)); // no route around (u, v) } }}When traversing from u to neighbour v, skip the edge leading back to the immediate parent.
If v has already been discovered, update low[u] = min(low[u], tin[v]) to record the back edge. If v is unvisited, recurse into v, then update low[u] = min(low[u], low[v]). If low[v] > tin[u], edge (u, v) is a bridge because v has no alternate route to u or above. Collecting all such edges runs in linear O(V + E) time with zero redundant traversals.
Example 3 · Sliding Puzzle Minimum Moves via State BFS
import java.util.ArrayDeque;import java.util.HashSet;import java.util.Queue;import java.util.Set;
public class SlidingPuzzlePracticeDemo { public static int minMoves(int[][] board) { StringBuilder sb = new StringBuilder(); for (int r = 0; r < 2; r++) { for (int c = 0; c < 3; c++) sb.append(board[r][c]); } String start = sb.toString(); String target = "123450"; if (start.equals(target)) return 0;
int[][] neighbors = { {1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4} };
Queue<String> q = new ArrayDeque<>(); Set<String> visited = new HashSet<>(); q.offer(start); visited.add(start);
int steps = 0; while (!q.isEmpty()) { int size = q.size(); steps++; for (int i = 0; i < size; i++) { String curr = q.poll(); int zero = curr.indexOf('0'); for (int nextPos : neighbors[zero]) { char[] chars = curr.toCharArray(); char tmp = chars[zero]; chars[zero] = chars[nextPos]; chars[nextPos] = tmp;
String next = new String(chars); if (next.equals(target)) return steps; if (visited.add(next)) q.offer(next); } } } return -1; }
public static void main(String[] args) { int[][] board = {{4, 1, 2}, {5, 0, 3}}; int moves = minMoves(board); System.out.println("Sliding puzzle moves: " + moves); }}Sliding puzzle moves: 5
What this code does
- Represents each 2x3 grid configuration as a 6-character string state.
- Transitions states by swapping '0' with adjacent grid neighbours in BFS.
- Finds the shortest sequence of 5 moves to solve the board configuration.
Finish up
Mark complete & continue
Next: What greedy means