This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Phase 3: Search and graphs
Grids and networks are graphs. Mark what you've visited and flood outward.
The question to ask
What are the nodes, what are the edges, and do I need everything connected (DFS) or the fewest steps (BFS)?
Islands, regions, networks, rooms, rotting fruit: once you see cells or entities connected by edges, it's a graph traversal. DFS (recursive or a stack) is simplest for "visit everything connected": counting islands, sizing regions, cloning. BFS (a queue) is required whenever the question asks for the shortest number of steps in an unweighted graph, and multi-source BFS starts from every source at once when they all spread together. Either way, a visited set is what keeps cycles from looping forever.
Want to watch it run first? Step through the interactive walkthrough.
Time O(V + E); O(rows × cols) for a grid · Space O(V)
Write it from memory first, in an editor or on paper, then check. Recalling it is what makes it stick; reading it again mostly doesn't.
Rotting Oranges: start the queue with every rotten orange, then spread one level per minute. Count the fresh ones up front so you know whether any were never reached.
function orangesRotting(grid: number[][]): number {
const rows = grid.length;
const cols = grid[0].length;
let frontier: [number, number][] = [];
let fresh = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 2) frontier.push([r, c]);
if (grid[r][c] === 1) fresh++;
}
}
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let minutes = 0;
while (frontier.length > 0 && fresh > 0) {
const next: [number, number][] = [];
for (const [r, c] of frontier) {
for (const [dr, dc] of directions) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && grid[nr][nc] === 1) {
grid[nr][nc] = 2;
fresh--;
next.push([nr, nc]);
}
}
}
frontier = next;
minutes++;
}
return fresh === 0 ? minutes : -1;
}The map doubles as the visited set: a node already in it has been copied, so return the copy instead of recursing forever around a cycle.
class GraphNode {
constructor(public val: number, public neighbors: GraphNode[] = []) {}
}
function cloneGraph(node: GraphNode | null): GraphNode | null {
const copies = new Map<GraphNode, GraphNode>();
function copy(original: GraphNode): GraphNode {
const existing = copies.get(original);
if (existing) return existing;
const clone = new GraphNode(original.val);
copies.set(original, clone);
clone.neighbors = original.neighbors.map(copy);
return clone;
}
return node ? copy(node) : null;
}Easy to hard. Read the prompt and name the signal before opening the tell. After each attempt, rate it: Again brings it back tomorrow, Hard holds the interval, Good and Easy push it further out.
Starting from one pixel of an image grid, recolour it and every 4-directionally connected pixel of the same original colour.
"Flood fill" through "4-directionally" connected cells is the base traversal. Watch the case where the new colour equals the old.
Not attempted yet
Given n nodes and a list of undirected edges, decide whether a valid path exists from source to destination in the graph.
"Path exists" in a "graph": build an adjacency list and run BFS or DFS from the source. Union-find also works.
Not attempted yet
Given a grid of '1' land and '0' water, count the islands: groups of land connected 4-directionally.
"Island" on a "grid": count connected components by flooding each unvisited land cell.
Not attempted yet
In a binary grid, return the area of the largest island of 4-directionally connected 1s.
Same flood fill as Number of Islands, but the DFS returns the size of what it sank.
Not attempted yet
Given a node in a connected undirected graph, return a deep copy (clone) of the graph.
"Clone" a "graph" with cycles: a Map from original to copy is both the result and the visited set.
Not attempted yet
Every minute, fresh oranges next to a rotten one become rotten. Return the minutes until none are fresh, or -1.
"Minutes" for "rotten" to spread from many cells at once: multi-source BFS, one level per minute.
Not attempted yet
Water flows to equal or lower neighbours. Return the cells in the grid from which water can reach both the Pacific and Atlantic ocean borders.
Searching from every cell is slow. Search backwards (uphill) from each "ocean" border, then intersect the two visited sets.
Not attempted yet
Capture every region of 'O' cells fully surrounded by 'X' by flipping it to 'X'. Regions touching the border survive.
Hard to prove a "region" is surrounded, easy to find the ones that aren't: flood from border 'O's, then flip everything else.
Not attempted yet
For each cell of a binary matrix, return the distance to the nearest 0.
"Nearest" of many sources: put every 0 in the queue and BFS outward once, rather than a BFS per cell.
Not attempted yet
Return the length of the shortest clear path from top-left to bottom-right of a binary grid, moving in 8 directions, or -1.
"Shortest path" on an unweighted "grid": BFS, with eight directions instead of four.
Not attempted yet
Return the number of words in the shortest transformation sequence from beginWord to endWord, changing one letter at a time through words in a list.
Shortest "transformation sequence": words are nodes, one-letter changes are edges, BFS gives the fewest steps. Wildcard keys like h*t find neighbours fast.
Not attempted yet