Practice · Backtracking · 4 of 4

Find a Word in a Letter Grid

You are given board, a grid of letters (each cell holds one uppercase letter), and a string word. Return true if you can spell word by starting at any cell and stepping to a neighbouring cell for each next letter, and false otherwise.

Neighbours share a side: up, down, left or right, never diagonally. A path may not use the same cell twice.

Example 1

Input
board = [["C", "A", "T", "S"], ["O", "R", "E", "D"], ["D", "O", "G", "E"]], word = "CARE"
Output
true
Start at the top-left C, step right to A, down to R, then right to E.

Example 2

Input
board = [["C", "A", "T", "S"], ["O", "R", "E", "D"], ["D", "O", "G", "E"]], word = "CODE"
Output
false
C, O and D run down the first column, but no E touches that D, and the other D has no O next to it.

Example 3

Input
board = [["C", "A", "T", "S"], ["O", "R", "E", "D"], ["D", "O", "G", "E"]], word = "ERE"
Output
false
The only E next to the R is the one you would start from, and a cell can't be used twice.

Constraints

  • The board has 1 to 6 rows and 1 to 6 columns.
  • word has 1 to 15 letters.
  • The board and word hold only uppercase English letters.