CodingNodes / Backtracking / Word Search System design Space play · ←→ step · R restart

Problem

You are given a grid of letters board and a string word. Decide whether the word can be spelled by walking through the grid.

Each next letter must be in a cell directly above, below, left or right of the previous one, and the same cell may not be used twice in one spelling. Letters are case sensitive. Return true if the word can be spelled, otherwise false.

Constraints

  • 1 ≤ rows, columns ≤ 6
  • 1 ≤ word.length ≤ 15
  • board and word contain only English letters (upper or lower case)

Examples: pick one to animate

Solutions

TimeO(m · n · 3^L) SpaceO(L)

Time: Any of the m·n cells can start a search. After the first letter each step has at most 3 new directions (the cell we came from is already used), and a path is at most L letters long.

Space: The recursion is at most L deep and the set of used cells holds at most L cells. The board itself is not changed.

Call go(r, c, k) to ask: can the letters from index k be spelled starting at cell (r, c)? It fails if the cell is off the board, already used, or holds the wrong letter. Otherwise mark the cell, try the four directions for letter k + 1, then unmark it so other paths can use it again. Run go from every cell.