Café Letter Board

MediumbacktrackingAlso known as Word Search

A café has a wall board of letter tiles in a grid. On quiz night, teams answer by tracing their word: start on any tile, then slide to the tile directly above, below, left or right for each next letter. Diagonal moves are not allowed, and a word cannot use the same tile twice.

The quiz host needs a quick check that an answer can really be traced on tonight's board.

Your task

Write canTrace(board, word). board is a list of equal-length strings, one per row, so board[r][c] is the letter in row r, column c. Return true if word can be traced as described, and false otherwise.

Consecutive letters must be on tiles that share a side, and each tile can be used at most once per word.

canTrace(board: string[], word: string) → bool

Examples

Example 1
Input
board = ["CAT", "ORE", "WEB"]
word = "CORE"
Output
true
Why

The board is
C A T
O R E
W E B
Start on C (top left), then down to O, right to R, right to E.

Example 2
Input
board = ["CAT", "ORE", "WEB"]
word = "BEER"
Output
false
Why

B touches both Es, but the two Es (row 1, column 2 and row 2, column 1) touch only diagonally, so you can never step from one to the other.

Example 3
Input
board = ["CAT", "ORE", "WEB"]
word = "RARE"
Output
false
Why

Spelling RARE would need to use the only R tile twice.

Constraints

  • 1 ≤ number of rows, number of columns ≤ 6
  • 1 ≤ word.length ≤ 15
  • board and word contain only uppercase letters A to Z.
Start with brute force

From every tile, follow every walk of the word's length (up to four choices per step) and compare letters at the end. On a 6 × 6 board with a 15-letter word that is 36 × 414, around 9.7 billion walks.

Almost all go wrong by the second or third letter. Check each letter as you step on it and turn back at once on a mismatch.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code