Trace a Word on the Letter Board
Medium · Backtracking · about 25 min
A puzzle board is a grid of uppercase letters, given as a list of equal-length strings (one string per row). You trace a word by starting on any cell with its first letter and then stepping up, down, left or right (no diagonals, and you cannot wrap from one edge to the other) onto the cell with the next letter. Each cell can be used at most once in one word.
Return True if word can be traced on the board, otherwise False.
- The board is 1×1 to 6×6.
wordhas 1 to 12 uppercase letters.
board_has_word(["CAT", "OXE", "DOG"], "DOGE") → True (D, O, G along the bottom row, then up to E)
board_has_word(["CAT", "OXE", "DOG"], "CXD") → False (C and X only touch on a diagonal)
Hints
- Try every cell as a start. Use a helper that knows the cell and how many letters are already matched.
- In the helper, give up if the cell is off the board, already used, or holds the wrong letter. Otherwise mark it and try the four neighbours.
- Unmark the cell before returning, whatever the result, so a different path can use it later.
Learn the pattern first: the Backtracking lesson.
More Backtracking problems
- Every Snack Bundle (Easy)
- Every Seating Plan (Easy)
- Keypad Spellings (Easy)
- Distinct Gift Bags (Medium)
- Exact Change Stacks (Medium)
- Mirror Word Splits (Medium)
- Peaceful Queens Count (Hard)