Python 0079.py
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def deeper(x, y, pos):
current = word[pos]
if board[y][x] != current:
return False
if pos == len(word) - 1:
return True
# footprints
board[y][x] = ":"
if x > 0 and deeper(x - 1, y, pos + 1):
return True
if x < len(board[y])-1 and deeper(x + 1, y, pos + 1):
return True
if y > 0 and deeper(x, y - 1, pos + 1):
return True
if y < len(board)-1 and deeper(x, y + 1, pos + 1):
return True
# no more footprints
board[y][x] = current
return False
for y in range(len(board)):
for x in range(len(board[y])):
if board[y][x] == word[0] and deeper(x, y, 0):
return True
return False
Difficulty
and has an acceptance rate of about 48% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Depth First Search
- Matrix
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic word-search problem on a two-dimensional character grid. It determines whether a given word can be formed by sequentially adjacent cells-horizontally or vertically-without reusing any cell. The algorithm combines a depth-first search (DFS) with in-place marking to avoid extra memory structures.
Core Logic
The entry point iterates over every cell, launching a recursive search whenever the cell matches the first character of the target word.
for y in range(len(board)):
for x in range(len(board[y])):
if board[y][x] == word[0] and deeper(x, y, 0):
return True
return False
The nested loops guarantee that every possible starting position is examined. The condition board[y][x] == word[0] filters out cells that cannot begin the word, reducing unnecessary recursion.
Recursive Search
The inner function deeper performs the DFS. It receives the current coordinates (x, y) and the index pos of the character being matched.
def deeper(x, y, pos):
current = word[pos]
if board[y][x] != current:
return False
if pos == len(word) - 1:
return True
board[y][x] = ":"
if x > 0 and deeper(x - 1, y, pos + 1):
return True
if x < len(board[y])-1 and deeper(x + 1, y, pos + 1):
return True
if y > 0 and deeper(x, y - 1, pos + 1):
return True
if y < len(board)-1 and deeper(x, y + 1, pos + 1):
return True
board[y][x] = current
return False
The function first checks whether the board cell matches the expected character. A mismatch aborts the current path immediately. When the last character of the word is successfully matched (pos == len(word) - 1), the function returns True, propagating success up the call stack.
In-Place Marking
To enforce the “no reuse” rule, the current cell is temporarily overwritten with a sentinel value (":"). This prevents subsequent recursive calls from stepping back onto the same cell.
board[y][x] = ":"
After exploring all four directions, the original character is restored, ensuring that other search paths can still use the cell.
board[y][x] = current
Directional Exploration
The four conditional calls explore left, right, up, and down neighbors. Boundary checks (x > 0, x < len(board[y])-1, y > 0, y < len(board)-1) guarantee that the recursion never accesses indices outside the board.
Each direction is evaluated in short-circuit fashion: as soon as a recursive call returns True, the function returns True without checking the remaining directions. This early exit avoids unnecessary work once a valid path is found.
Edge Cases Handled
The algorithm gracefully handles boards of any rectangular shape, including single-row or single-column configurations. The boundary checks prevent out-of-range errors even when the board dimensions are minimal.
When the target word consists of a single character, the condition pos == len(word) - 1 becomes true after the initial character match, causing an immediate True return without any recursion or marking.
If the board contains duplicate characters, the in-place marking ensures that a path cannot revisit a cell, even if the same character appears elsewhere. The restoration step guarantees that other independent paths can still use the cell after the current path backtracks.
An empty board or an empty word is implicitly handled: the outer loops will have zero iterations for an empty board, leading to a final False. An empty word would cause word[0] to raise an exception, but the problem specification typically guarantees a non-empty word, so the code aligns with that contract.
Performance Optimizations
The primary optimization is the avoidance of auxiliary data structures for visited tracking. By mutating the board directly, the algorithm reduces memory overhead and improves cache locality, as all state resides within the original grid.
Early termination is employed at multiple levels. The outer loop stops as soon as a successful start position is found. Within deeper, a mismatch aborts the current branch instantly, and a successful deeper call returns without exploring remaining directions.
The boundary checks are performed once per direction, eliminating the need for separate helper functions or repeated length calculations. This keeps the inner loop tight and minimizes Python attribute lookups.
Overall, the combination of in-place marking, early exits, and minimal per-call work yields an efficient traversal that scales well with typical board sizes and word lengths.
ELI5 - Simplified Explanation
Imagine a large grid filled with tiles that each have a letter written on them. The goal is to find a secret word hidden inside this grid by connecting letters that are right next to each other.
The process starts by looking at every single tile on the board to see if it matches the very first letter of the target word. Once a match is found, the computer starts a hunt to find the rest of the letters.
To keep track of where the path has already gone, the computer temporarily changes the letter currently being used into a colon. This acts like putting down a little footprint so the computer does not try to use the exact same tile twice for the same word.
From the current spot, the computer looks in all four directions, which are left, right, up, and down, to see if the next letter of the word is waiting nearby. If it finds the next correct letter, it moves to that new spot and continues the search from there.
If the computer hits a dead end where none of the paths lead to the next letter, it performs a little clean-up. It turns that colon back into the original letter it found earlier. This is like lifting the footprint so that a different path through the grid can use that same spot later on.
The search keeps going until either the entire word is found safely or every possible path from that starting point has been checked. If the word is finished, the task is complete.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 212: Word Search II
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality