Trace a Phrase Through Neighboring Tiles
Trees & GraphsAuto-graded · 22 test casesLast updated
Decide whether a string can be traced through a rectangular letter grid by stepping to up/down/left/right neighbors without reusing a cell, using backtracking search.
Trace a Phrase Through Neighboring Tiles
You are given a rectangular grid of single-character tiles and a target string. Decide whether the target can be spelled by walking across the grid.
A valid walk:
- starts on any tile you like,
- reads the target's characters in order, one per tile, so the tile visited at step
imust hold exactly the charactertarget[i], - moves from each tile to a tile directly above, below, to the left, or to the right (diagonal moves are not allowed),
- never visits the same tile twice within one walk.
Return True if at least one valid walk spells the target, and False otherwise.
Letter comparison is case-sensitive: 'a' and 'A' are different characters.
Input
grid: a list ofmrows, each a list ofnstrings, where every string is a single English letter.target: a string of English letters.
Output
A boolean: True if the target can be traced, False otherwise.
Constraints
m == len(grid)andn == len(grid[i])for every rowi1 <= m, n <= 61 <= len(target) <= 15gridandtargetcontain only lowercase and uppercase English letters- The input grid should not be left modified after your function returns
Notes
- A target longer than the number of tiles (
m * n) can never be traced. - A grid with a single tile can only match a one-character target equal to that tile.
- When a tile is rejected on one attempted route, it must still be available to other routes.
Examples
Example 1
Input: can_trace_phrase([['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']], 'ABCCED')
Output: True
Example 2
Input: can_trace_phrase([['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']], 'ABCB')
Output: False
Hints
Hint 1
Try every tile as a possible starting point, then explore neighbors recursively while tracking which index of the target you are trying to match.
Hint 2
Mark the current tile as used before exploring its neighbors, and un-mark it afterward so other routes can use it (backtracking).
Hint 3
To prune: if the target needs more copies of some letter than the grid contains, return False immediately. Also, a walk spelling the target forward spells its reverse backward, so you may start from whichever end letter is rarer in the grid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every tile as a possible start of the walk. From a tile that matches the current target character, recurse into its four neighbors looking for the next character. This is a standard backtracking depth-first search with three steps:
- Choose: temporarily mark the current tile as used (the reference overwrites it with
None, which never equals a letter). - Explore: recurse up, down, left and right with the next index.
- Undo: put the original character back so other routes can use the tile.
Two cheap pruning steps run first:
- Letter counts. If the target needs more copies of some letter than the grid holds, no walk can exist (each tile is used at most once), so return
False. This also avoids exponential searches that are doomed to fail. - Direction choice. A walk spelling the target forward spells the reversed target backward, because adjacency is symmetric. If the first letter is more common in the grid than the last, reverse the target so fewer starting tiles match.
Also, if the target is longer than m * n, return False at once.
Why it is correct
- Completeness: every valid walk begins at some tile, and the outer loop tries all of them. At each step the search tries every unused neighbor, so an existing walk will be found.
- Soundness: a branch returns
Trueonly after every character matched in order via adjacent tiles, and the marker guarantees no tile repeats on the current path. - State restoration: the tile is restored after exploring, whether or not the branch succeeded, so failed routes never affect later ones and the grid is unchanged on return.
- Pruning is safe: the count check only rejects impossible targets, and reversing the target does not change whether a walk exists.
Complexity
Let L = len(target).
- Time:
O(m * n * 3^L)worst case:m * nstarts, up to 4 choices at the first step and at most 3 afterward, since the previous tile is marked. The counting pass costsO(m * n + L). Pruning makes it fast in practice for the given limits. - Space:
O(L)for the recursion stack; the grid is marked in place, and the counters hold at most 52 letters.
Reference solution
from collections import Counter
from typing import List
def can_trace_phrase(grid: List[List[str]], target: str) -> bool:
rows = len(grid)
cols = len(grid[0]) if rows else 0
if not target:
return True
if len(target) > rows * cols:
return False
grid_counts = Counter(ch for row in grid for ch in row)
target_counts = Counter(target)
if any(count > grid_counts[ch] for ch, count in target_counts.items()):
return False
# Start from the rarer end; a reversed path is still a valid path.
if grid_counts[target[0]] > grid_counts[target[-1]]:
target = target[::-1]
last = len(target) - 1
def search(r, c, index):
if grid[r][c] != target[index]:
return False
if index == last:
return True
ch = grid[r][c]
grid[r][c] = None # mark as used on the current path
found = (
(r > 0 and search(r - 1, c, index + 1)) or
(r + 1 < rows and search(r + 1, c, index + 1)) or
(c > 0 and search(r, c - 1, index + 1)) or
(c + 1 < cols and search(r, c + 1, index + 1))
)
grid[r][c] = ch # backtrack
return found
return any(search(r, c, 0) for r in range(rows) for c in range(cols))