iq.lab
Python starts when a code cell comes near or you run one
mediumBacktrackingDepth-first search target 25 min

You get a grid of letters board (a list of rows, each row a list of one-letter strings) and a string word. Return True if word can be spelled along a path on the board, and False otherwise.

A path starts on any cell and moves one cell at a time up, down, left or right, never diagonally. The cells along the path, in order, must hold the letters of word, and no cell may appear twice on one path. Two cells that hold the same letter are still two different cells.

Your function may change cells while it searches, but board must hold its original letters again when the function returns.

Example 1
Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "CORE"OutputTrue

Start on the C at the top left, step down to O, right to R, and right again to E.

Example 2
Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "RARE"OutputFalse

From the only R, step up to A. The only R next to that A is the one already on the path, and a cell cannot be used twice.

Example 3
Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "ACORN"OutputFalse

A, C, O and R join up, but the only N touches that R at a corner. Diagonal steps are not allowed.

Constraints
  • 1 ≤ number of rows, number of columns ≤ 6

  • 1 ≤ len(word) ≤ 15

  • board and word hold only English letters.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.