Skip to content
BytePatterns

Trace a Word Through a Letter Grid

MediumBacktracking#backtracking#grid-dfs#pruning~25m

Problem

Given a grid of letters as a list of equal-length strings and a word, decide whether the word can be traced through the grid. A trace starts on any cell, moves one step up, down, left or right for each next letter, and never uses the same cell twice. Return True if some trace spells the whole word, otherwise False.

Examples

Input:  board = ["ABCE", "SFCS", "ADEE"], word = "ABCCED"
Output: True
Why:    A B C across the top row, down to the second C, then E and D along the bottom
Input:  board = ["ABCE", "SFCS", "ADEE"], word = "ABCB"
Output: False
Why:    the only B next to that C is the one already used
Input:  board = ["A"], word = "AA"
Output: False
Why:    edge case, the word needs more cells than the grid has

Hints

0 / 3

Stuck on the idea rather than the code? Word Search & Pruning covers it.