Skip to the code
cf.
+25 XP

#311 Trace a Word in a Letter Grid

medium

A word game shows a grid of letter tiles, given as board, an array of equal-length strings. The player spells a word by starting on any tile and moving to a tile directly above, below, left, or right each time. A tile can be used at most once per word.

Write canTrace(board, word) that returns true if word can be spelled this way, and false otherwise.

Example 1

Input: board = ["CAT","XOR","DOG"], word = "CAT"
Output: true

The top row spells CAT from left to right.

Example 2

Input: board = ["CAT","XOR","DOG"], word = "COG"
Output: false

The only C has neighbors A and X, never O.

Constraints

  • 1 <= board.length, board[0].length <= 6
  • 1 <= word.length <= 15
  • Uppercase letters only.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).