Word Search II
TriesMatrixDFS
HardLeetCode #212
Problem Statement
Given an m x n
board of characters and a list of strings words
, return all words on the board that can be formed by traversing adjacent cells (horizontally or vertically). Each letter on the board can only be used once in each word.
Example Board
O
A
A
N
E
T
A
E
I
H
K
R
I
F
L
V
Words to find: ["oath", "pea", "eat", "rain"]
Output: ["eat", "oath"]
Explanation:
- "eat" exists on the board
- "oath" exists on the board
- "pea" and "rain" are not on the board
Trie Structure
Found Word Path
Complete Word
Approach:
- Build a trie from the word list
- Use DFS to explore board paths
- Check if current path exists in trie
- Mark visited cells to avoid reuse
Key Concepts
- • Use trie to efficiently store and search word prefixes
- • DFS with backtracking to explore all possible paths
- • Track visited cells to prevent reuse
- • Time complexity: O(M × N × 4^L) where L is max word length
- • Space complexity: O(total characters in all words)
Algorithm Explanation
This solution combines a Trie for efficient word lookup with DFS for board traversal. The Trie helps us quickly validate if our current path could form a valid word.
Key Operations
- Build Trie: Create a trie from the word list for efficient prefix checking.
- Board DFS: For each cell, explore all possible paths using depth-first search.
- Word Validation: Use trie to check if current path forms a valid word.
- Track Visited: Mark cells as visited during DFS to avoid reusing them.
Optimization Tips
- Stop DFS when current path is not a valid prefix in trie
- Remove words from trie after finding them to avoid duplicates
- Use board cell itself as visited marker to save space
- Track found words in a set for O(1) lookup
Word Search Visualization
Finding words in the grid using Trie + DFS
Board
O
A
A
N
E
T
A
E
I
H
K
R
I
F
L
V
Found Words
oath
pea
eat
rain
Start: Initialize search
Starting the word search...
Step 1 of 54
Code Example