All coding questions

Word Search

medium
NeetCode 150backtrackingdfsmatrix

Problem

Given a grid of letters and a word, decide whether the word can be spelled by a path of adjacent cells moving horizontally or vertically. The same cell may not be reused within one path.

Examples

Input: grid spelling paths, word = "ABCCED"
Output: true
A connected path spells the word.
Input: same grid, word = "ABCB"
Output: false
Reusing the B cell is not allowed.

Constraints

  • 1 <= rows, cols <= 6
  • 1 <= word.length <= 15
Hints(tap to reveal)
  • 1. Start a DFS from every matching first letter.
  • 2. Mark cells visited during a path and unmark on backtrack.
Optimal approach(spoiler)
  1. For each cell matching the first character, launch a depth-first search.
  2. Match successive letters by moving to unvisited adjacent cells.
  3. Temporarily mark the current cell to prevent reuse, then restore it on return.
  4. Succeed when the whole word is matched.
  5. O(rows * cols * 4^len) worst case.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor