Café Letter Board

MediumbacktrackingAlso known as Word Search

A café has a wall board of wooden letter tiles in a grid. On quiz night, teams answer by tracing their word on the board: they start on any tile and slide a finger to a tile directly above, below, left or right for each next letter. Diagonals are not allowed, and no tile may be used twice in the same word.

The quiz host wants a quick way to check whether a team's 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), go down to O, right to R, right to E. Every step moves to a side neighbour.

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 each other only diagonally. Diagonal steps are not allowed, so you can never step from one E to the other.

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

R, A, R would need the R tile twice: there is only one R, and a tile cannot be used twice in the same word.

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 possible walk of the word's length (up to four choices per step) and compare the letters only at the end. On a 6 × 6 board with a 15-letter word that is 36 × 414, around 9.7 billion walks.

Almost all of them go wrong on the second or third letter. Checking each letter the moment you step on it, and turning back right away when it does not match, removes nearly all of that work.

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