Graphs hidden in problems
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many algorithmic puzzles hide implicit graphs where valid game configurations form vertices and valid moves form edges.
Implicit graphs: states as nodes and moves as edges
Many interview problems never provide an explicit graph with adjacency lists. Instead, a valid configuration of the puzzle or game represents a state vertex. Any legal move that transitions one configuration to another forms a directed edge.
Example 1 · Word Ladder Shortest Transformation
import java.util.ArrayDeque;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Queue;import java.util.Set;
public class WordLadderDemo { public static int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> dict = new HashSet<>(wordList); if (!dict.contains(endWord)) return 0;
Queue<String> queue = new ArrayDeque<>(); queue.offer(beginWord); int steps = 1;
while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String curr = queue.poll(); if (curr.equals(endWord)) return steps;
char[] chars = curr.toCharArray(); for (int j = 0; j < chars.length; j++) { char orig = chars[j]; for (char c = 'a'; c <= 'z'; c++) { chars[j] = c; String next = new String(chars); if (dict.remove(next)) { queue.offer(next); } } chars[j] = orig; } } steps++; } return 0; }
public static void main(String[] args) { String begin = "hit"; String end = "cog"; List<String> words = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"); int len = ladderLength(begin, end, words); System.out.println("Ladder length: " + len); }}Ladder length: 5
What this code does
- Transforms words by substituting one character at a time among 26 alphabet letters.
- Removes visited words from the dictionary set to prune cycles and avoid duplicate visits.
- Sequence "hit" -> "hot" -> "dot" -> "dog" -> "cog" contains 5 words.
Brute force recursive search explores moves blindly, frequently revisiting previously seen states. Without memoization, the search tree expands exponentially as O(b^d), where b is branching factor. State space search tracks visited configurations in a hash set to prune repeated exploration. Breadth-first search over states guarantees finding the minimum number of transitions. Because every state transition carries a uniform step cost of 1, BFS is optimal. This transforms intricate game puzzles into standard shortest path traversals.
BFS over state transitions: open the rotary lock
Consider a combination lock with four circular wheels, each showing digits 0 to 9. Each move turns any single wheel forward or backward by one position. Turning 0 backward wraps around to 9, and turning 9 forward wraps to 0.
A list of deadend combinations permanently blocks the lock if entered.
Example 2 · Open the Lock via BFS State Search
import java.util.ArrayDeque;import java.util.Arrays;import java.util.HashSet;import java.util.Queue;import java.util.Set;
public class OpenLockDemo { public static int openLock(String[] deadends, String target) { Set<String> dead = new HashSet<>(Arrays.asList(deadends)); if (dead.contains("0000")) return -1; if (target.equals("0000")) return 0;
Queue<String> queue = new ArrayDeque<>(); Set<String> visited = new HashSet<>(); queue.offer("0000"); visited.add("0000");
int steps = 0; while (!queue.isEmpty()) { int size = queue.size(); steps++; for (int i = 0; i < size; i++) { String curr = queue.poll(); for (int wheel = 0; wheel < 4; wheel++) { char[] chars = curr.toCharArray(); char orig = chars[wheel];
// Turn up chars[wheel] = (orig == '9') ? '0' : (char) (orig + 1); String up = new String(chars); if (up.equals(target)) return steps; if (!dead.contains(up) && visited.add(up)) queue.offer(up);
// Turn down chars[wheel] = (orig == '0') ? '9' : (char) (orig - 1); String down = new String(chars); if (down.equals(target)) return steps; if (!dead.contains(down) && visited.add(down)) queue.offer(down); } } } return -1; }
public static void main(String[] args) { String[] deadends = {"0201", "0101", "0102", "1212", "2002"}; String target = "0202"; int turns = openLock(deadends, target); System.out.println("Minimum turns to open: " + turns); }}Minimum turns to open: 6
What this code does
- Treats each 4-digit code as a graph node with 8 outgoing edges (4 wheels * 2 directions).
- Explores states level by level using BFS to guarantee the minimum number of moves.
- Finds the shortest sequence to "0202" in 6 turns while skipping deadend states.
The initial state is the string "0000". From any state, exactly eight immediate neighbouring states can be reached. Breadth-first search enqueues "0000" with step count 0 and marks it visited. At each level, poll the current combination and generate all eight candidate wheel turns.
Discard any candidate state that appears in the deadend set or visited set. Enqueue valid candidates and record their distance. When the target combination is polled, the current queue depth is the minimum moves.
Bitmask states for visited tracking and collection puzzles
Some puzzles require collecting keys or items before reaching an exit. In such problems, a state cannot simply be the learner's grid coordinate (r, c). Revisiting a previously crossed cell is often necessary after obtaining a new key.
Example 3 · Bitmask State Grid Traversal
import java.util.ArrayDeque;import java.util.Queue;
public class GridKeysDemo { static class State { int r, c, mask, dist; State(int r, int c, int mask, int dist) { this.r = r; this.c = c; this.mask = mask; this.dist = dist; } }
public static int shortestPathAllKeys(String[] grid) { int rows = grid.length; int cols = grid[0].length(); int maxKey = 0; int startR = 0, startC = 0;
for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { char ch = grid[r].charAt(c); if (ch == '@') { startR = r; startC = c; } else if (ch >= 'a' && ch <= 'f') { maxKey = Math.max(maxKey, ch - 'a' + 1); } } }
int targetMask = (1 << maxKey) - 1; boolean[][][] visited = new boolean[rows][cols][1 << maxKey]; Queue<State> queue = new ArrayDeque<>(); queue.offer(new State(startR, startC, 0, 0)); visited[startR][startC][0] = true;
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; while (!queue.isEmpty()) { State curr = queue.poll(); if (curr.mask == targetMask) return curr.dist;
for (int[] d : dirs) { int nr = curr.r + d[0]; int nc = curr.c + d[1]; if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue; char ch = grid[nr].charAt(nc); if (ch == '#') continue;
int nextMask = curr.mask; if (ch >= 'a' && ch <= 'f') nextMask |= (1 << (ch - 'a')); if (ch >= 'A' && ch <= 'F') { if ((curr.mask & (1 << (ch - 'A'))) == 0) continue; // Locked }
if (!visited[nr][nc][nextMask]) { visited[nr][nc][nextMask] = true; queue.offer(new State(nr, nc, nextMask, curr.dist + 1)); } } } return -1; }
public static void main(String[] args) { String[] grid = { "@.a.#", "###.#", "b.A.B" }; int steps = shortestPathAllKeys(grid); System.out.println("Steps to collect all keys: " + steps); }}Steps to collect all keys: 8
What this code does
- Augments spatial grid coordinates (r, c) with an integer bitmask storing acquired keys.
- Allows cells to be revisited whenever the player holds a strictly newer set of keys.
- Finds the shortest path collecting both keys 'a' and 'b' in exactly 8 steps.
Therefore, the complete state must consist of coordinates and the set of keys collected. Storing a collection object per state consumes excessive heap memory and hashing overhead. An integer bitmask represents subsets of up to 30 keys with blazing speed. If key k is acquired, set bit (1 << k) using bitwise OR. The state space size becomes rows * cols * 2^K, where K is the number of keys. For K <= 10, 2^10 is 1024, enabling fast 3D boolean array indexing visited[r][c][mask]. BFS explores this augmented state space to find the shortest path.
Next step
Check your understanding
10 quick questions