Word Search [Medium] — DFS Backtracking on Grid
Search for a word in a 2D grid using DFS backtracking with in-place visited marking.
webcoderspeed.com
95 articles
Search for a word in a 2D grid using DFS backtracking with in-place visited marking.
Find the longest nested set S(k) in a permutation array by tracing cycles with visited marking in O(n) time.
Master BFS and DFS on graphs and grids: islands, flood fill, shortest paths, connected components, and multi-source BFS with 5-language implementations.
Count connected land components in a binary grid using DFS flood fill or BFS. Classic easy problem, foundation for all island variants.
Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.
Calculate the perimeter of an island in a binary grid. Each land cell contributes 4 edges minus 2 for each land neighbour.
Find the maximum area of any island in a binary grid. DFS returns the area of each island, track the maximum.
Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.
Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.
For each cell find distance to nearest 0. Multi-source BFS from all 0s simultaneously gives optimal O(m*n) solution.
Fill each empty room with distance to nearest gate. Multi-source BFS from all gates (0) simultaneously, walls (-1) are barriers.
Count land cells that cannot reach the border. Boundary DFS marks all reachable land from borders, then count remaining land cells.
Count islands in grid2 that are subsets of islands in grid1. DFS the island in grid2 and verify every cell is also land in grid1.
Find the largest island after flipping exactly one 0 to 1. Color each island with DFS, store sizes, then check each 0 cell's unique neighbour islands.
Find cells that can flow to both Pacific and Atlantic oceans. Run DFS backwards from each ocean border, find intersection.
Find shortest clear path from top-left to bottom-right in binary matrix using 8-directional BFS. Return path length or -1.
Find the water cell farthest from any land. Multi-source BFS from all land cells gives each water cell its min distance to land.
Search for a word in a grid by moving to adjacent cells without reuse. DFS with backtracking: mark visited, recurse, unmark.
Count islands with distinct shapes. Encode each island's DFS traversal path as a string to capture shape, store in a set.
Count islands fully surrounded by water (no border touch). Flood-fill border land first, then count remaining connected land components.
Find minimum flips to connect two islands. DFS to find and color first island, then BFS outward until reaching second island.
Find path from top-left to bottom-right minimizing maximum absolute difference between consecutive cells. Use Dijkstra or binary search + BFS.
Count islands after each addLand operation. Online version requires Union-Find: add each land cell and union with adjacent land cells.
Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.
Count connected components in an undirected graph given as adjacency matrix. DFS or Union-Find both work.
Determine if all rooms are reachable. Start from room 0, DFS using keys found in each room to unlock new rooms.
Check if a path exists between source and destination in an undirected graph. BFS from source or Union-Find both work in O(V+E).
BFS from entrance in a maze to find nearest exit (border empty cell). Classic BFS shortest path with exit condition.
Minimum dice rolls to reach square n^2. Convert board position to 2D coordinates (Boustrophedon order), BFS on board states.
Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.
Check if you can reach a 0 in the array by jumping arr[i] steps left or right. BFS/DFS from start index.
Determine if you can finish all courses given prerequisites. Equivalent to detecting a cycle in a directed graph using BFS (Kahn) or DFS coloring.
Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.
Check if n nodes and edges form a valid tree: must be connected and acyclic. Exactly n-1 edges, all connected via BFS/DFS or Union-Find.
Count connected components in an undirected graph. Union-Find or BFS both give O(V+E) solution.
Find the edge that creates a cycle in an undirected graph that started as a tree. Process edges with Union-Find; the first edge whose endpoints share a root is redundant.
Find all paths from node 0 to node n-1 in a DAG. DFS with backtracking: explore each path, add to results when destination reached.
Find time for signal to reach all nodes. Single-source shortest path (Dijkstra) from node k; answer is max of all shortest distances.
Find cheapest flight from src to dst with at most k stops. Bellman-Ford with k+1 iterations or BFS level-by-level.
Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.
Find ALL shortest transformation sequences. BFS builds layer map, DFS reconstructs all paths backwards from endWord to beginWord.
Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.
Check if people can be split into two groups with no dislikes within a group. Equivalent to bipartite check on dislikes graph.
Check if a graph can be 2-colored such that no adjacent nodes share a color. BFS/DFS 2-coloring on all connected components.
BFS with (position, last_jumped_back) state to find min jumps home avoiding forbidden positions. State space BFS avoids revisiting same position+direction.
Evaluate queries like A/C = A/B * B/C. Build weighted directed graph from equations, BFS/DFS to multiply edge weights along paths.
Count total reachable nodes in a subdivided graph within M moves. Dijkstra from node 0 gives max remaining moves at each node; use those to count subdivisions.
Complete cheatsheet for BFS and DFS on graphs and grids: 7 patterns, complexity table, common pitfalls, and problem index.
Find if a BST contains two nodes summing to target using a hash set during DFS traversal.
Flatten a multilevel doubly linked list by inserting child sub-lists inline using DFS or an explicit stack.
Count islands in a 2D grid using BFS or DFS to flood-fill connected land cells, marking them visited.
Find the maximum depth of a binary tree using recursive DFS (one line) or iterative BFS level counting.
Invert a binary tree by recursively swapping left and right children at every node.
Check if a binary tree is symmetric by comparing mirror subtrees with a two-pointer recursive approach.
Determine if a root-to-leaf path exists with a given sum using DFS that subtracts each node value from the target.
Check if two binary trees are identical by recursively comparing structure and node values.
Check if a binary tree is height-balanced by computing subtree heights and returning -1 early on imbalance.
Merge two binary trees by adding overlapping node values recursively, using existing nodes where possible.
Sum all BST values in [low, high] using BST property to prune entire subtrees outside the range.
Collect all root-to-leaf paths with a given sum using DFS backtracking, appending and removing the current node.
Find the diameter (longest path between any two nodes) using a depth function that tracks the maximum path through each node.
Validate a BST by passing down min and max bounds through DFS, ensuring every node falls strictly within its valid range.
Find the LCA of two nodes using post-order DFS: return root when found, propagate upward and split at the ancestor.
Count paths in a binary tree summing to target (not necessarily root-to-leaf) using a prefix sum frequency map.
Flatten a binary tree to a linked list in-place using pre-order traversal order.
Find all nodes at distance K from a target node by building parent pointers then doing BFS.
Compute the total sum of all root-to-leaf numbers formed by concatenating digits along each path.
Count nodes where no node on the root-to-node path has a value greater than the node itself.
Replace each node value with the sum of all values greater than or equal to it using reverse in-order traversal.
Find all duplicate subtrees by serializing each subtree and using a hash map to detect duplicates.
Find path directions between two tree nodes by finding LCA then building paths from LCA to each target.
Count minimum moves to distribute coins evenly by tracking excess/deficit coins flowing through each edge.
Find the maximum path sum in a binary tree where the path can start and end at any node.
Serialize a binary tree to string and back using BFS level-order or DFS preorder with null markers.
Collect leaves by height (distance from leaf) repeatedly, returning all leaves at each height level.
Find minimum seconds to collect all apples in a tree by DFS: include a subtree path only if it contains apples.
Find the maximum |a - b| for any ancestor-descendant pair by tracking min and max values along each root-to-leaf path.
Find the longest zigzag path in a binary tree where you alternate left-right directions at each step.
Compute sum of distances from every node to all others in O(n) using two DFS passes with rerooting technique.
Remove all subtrees that do not contain a 1 by recursively returning null for subtrees with only zeros.
Find lexicographically smallest string from any leaf to root by collecting and comparing reversed paths.
Sum all root-to-leaf path sums in a tree encoded as 3-digit integers using a hashmap to decode tree structure.
Transform a binary tree so every right child becomes a sibling and left child becomes parent using iterative rotation.
Find second minimum value in a special binary tree where root is min and each node equals min of its children.
Build a preorder string representation of a binary tree using parentheses to show tree structure.
Traverse an N-ary tree in preorder and postorder using DFS with a stack or recursion.
Count nodes where node value equals the average of all values in its subtree using post-order DFS returning sum and count.
Trie that supports wildcard '.' matching any character. DFS through trie when '.' encountered, trying all children.
Find all words from a list in a grid. Build trie from words, DFS on grid while traversing trie simultaneously to prune early.
Find all strongly connected components in a directed graph using Tarjan's single-pass DFS algorithm with discovery time, low-link values, and a stack.
Find all bridge edges and articulation point vertices in an undirected graph using a single DFS pass with discovery time and low-link tracking.
Find the itinerary using all flight tickets exactly once (Eulerian path). Uses Hierholzer's algorithm: DFS with post-order insertion into result — the only graph algorithm that uses post-order for path construction.
Find the longest path in a directed acyclic graph using DFS with memoisation. Since cycles are absent, DFS never revisits nodes, making top-down DP straightforward.
Word Search I and II solved with DFS backtracking. Word Search II uses a Trie to prune the search space from O(N·4^L) per word to O(N·4^L) total for all words.
Create a deep copy of an undirected graph using DFS with a HashMap to track visited/cloned nodes. Meta tests this to evaluate graph traversal and pointer manipulation.