04
Implicit graph / state BFS (Graph BFS / DFS Sub-pattern)
The nodes aren't given; they are states (codes, words, squares) and you generate each state's neighbours when you pop it.
Signals in the problem statement
- ›
"minimum number of moves / turns / transformations"
- ›
a rule for one move: turn one wheel, change one letter, a knight's jump, a dice roll
- ›
a set of forbidden states (deadends, word list)
What makes it different
Knight and Open the Lock are the template: neighbours come from a fixed list of moves. Snakes and Ladders needs a square → (row, col) mapping and takes a snake or ladder at most once per move. The Maze only counts cells where the ball stops, not every cell it rolls over. Word Ladder builds neighbours by trying all 26 letters at each position and counts words, not changes.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Minimum Steps to Reach Target by a KnightWalkthroughMediumBasic Anchor·GeeksforGeeks
- 2Open the LockWalkthroughMediumBasic Reinforcement·LeetCode #752
- 3Snakes and LaddersWalkthroughMediumSlight Variation·LeetCode #909
- 4The MazeWalkthroughMediumMedium·LeetCode #490 Premium
- 5Word LadderWalkthroughHardPattern Transfer·LeetCode #127
Template
state-bfs-template.cpp
// State BFS: nodes are states (strings here), neighbours are generated on the fly.
int minMoves(const string& start, const string& goal, const unordered_set<string>& blocked) {
if (blocked.count(start)) return -1;
unordered_map<string, int> dist{{start, 0}};
queue<string> q;
q.push(start);
while (!q.empty()) {
string s = q.front(); q.pop();
if (s == goal) return dist[s];
for (int i = 0; i < (int)s.size(); i++)
for (int step : {1, 9}) { // one wheel up or down (Open the Lock)
string t = s;
t[i] = char('0' + (t[i] - '0' + step) % 10);
if (blocked.count(t) || dist.count(t)) continue;
dist[t] = dist[s] + 1;
q.push(t);
}
}
return -1;
}Remember this · Graph BFS / DFS
Trigger
Grid of cells, islands, regions, "minimum steps", transformations between states, connected components.
Think
What is a node, what is an edge, and do I need the shortest path or just reachability?
Key question
How do I mark visited so I never process a node twice?