Word Search

MediumBacktracking

You get a board of letters and a word. Return true if the word can be spelled by a path through the board, and false otherwise.

Each step of the path moves to a cell up, down, left or right of the last one, and a path may not use the same cell twice. On this page the board is written as an array of rows, top row first, each cell a one-letter string. Upper and lower case are different letters.

Examples

Example 1
Input:  board = [["c", "a", "t"], ["x", "r", "s"], ["d", "o", "g"]], word = "cars"
Output: true

c at the top left, right to a, down to r, right to s.

Example 2
Input:  board = [["c", "a", "t"], ["x", "r", "s"], ["d", "o", "g"]], word = "cog"
Output: false

The only c has a and x beside it, never an o.

Constraints

  • 1 ≤ m, n ≤ 6 for a board of m rows and n columns
  • 1 ≤ word.length ≤ 15
  • The board and the word use English letters, upper and lower case.

Stuck?

Hint 1

Try every cell as the start. From a cell that matches the next letter, try each of its four neighbors for the letter after it: a depth-first search with backtracking.

Hint 2

Mark a cell as used while it is on the current path, and unmark it when you step back off it, so another path can still use it.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 12 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur