Word Search II
Find which words from a list exist as adjacent-cell paths in a letter grid (no cell reused per word).
Open on LeetCode ↗Intuition
Running one grid-DFS per word repeats the same walks over and over. Instead put ALL words into a trie and run one DFS per grid cell, moving through grid and trie together: a step is only taken if the trie has that child, so the search dies the instant no word can match. Hitting a word-flag records a hit — the trie searches every word simultaneously.
Approach
Trie of all words
Insert every word; store the full word at its end node (no separate flag needed — the word itself is the flag).
DFS grid and trie in lockstep
From each cell whose letter is a trie child of the root: mark the cell visited, recurse into neighbors whose letters continue the trie path, unmark on return. Missing child = instant prune.
Dedupe and prune harder
On finding a word, null its marker so it is reported once. Optionally delete leaf trie nodes after exhausting them — the trie shrinks as words are found, speeding later cells.
Solution & live demo
Edge cases
Clearing the end-node marker on first find prevents duplicates.
Interior end-markers fire without stopping the deeper search.
Temporary '#' marking blocks revisits; restored on backtrack.