Word Search

Medium#79path on a grid

You get a board of letters and a word. Say whether the word can be read along a path of cells, each next cell touching the one before it up, down, left or right, with no cell used twice. Our example: the board TE / OT / TO and the word TOTE → true.

input
board: a grid of letters, m rows of n each; word: a string.
returns
true if word can be read along a path of cells, each next one beside the one before it (above, below, left or right) and no cell used twice, otherwise false. Upper and lower case letters differ.
constraints
  • 1 ≤ m = board.length ≤ 6
  • 1 ≤ n = board[i].length ≤ 6
  • 1 ≤ word.length ≤ 15
  • board and word: English letters, upper and lower case
our 17 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
function exist(board, word) {

}
Ctrl ↵
format
reset

saved in this browser

17 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more backtracking problems

Pattern “Backtracking” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.