#79

Word Search

Medium Grid DFS backtracking

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Decide whether a word can be traced in a letter grid by moving up, down, left or right, without reusing a cell.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: can you trace the word through neighbouring cells without reusing a cell?

Why this works: DFS from each matching start cell; mark cells on the current path and unmark them when you go back.

Example: word "SEE" on [[A,B,C,E],[S,F,C,S],[A,D,E,E]]

start S at (1,3) → E at (2,3) → E at (2,2) ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to restore the cell, which blocks other paths that need it.

Solve on LeetCode ↗
Complexity
  • Time: O(m · n · 3^L), L = word length.
  • Space: O(L) recursion.
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon