KatInterview

Trace a Phrase Through Neighboring Tiles

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbacktrackingdfsmatrix

Last 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 i must hold exactly the character target[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 of m rows, each a list of n strings, 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) and n == len(grid[i]) for every row i
  • 1 <= m, n <= 6
  • 1 <= len(target) <= 15
  • grid and target contain 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.