☰ All problems

Word Search

MediumBacktrackingMatrixDFS

In a tablet word game, players spell words by dragging a finger across a grid of letter tiles, board. A drag can start on any tile and then moves one tile at a time up, down, left or right, never diagonally, and no tile may be used twice in the same word. Uppercase and lowercase letters are different tiles.

Given board and a word, return true if the word can be spelled with a single drag, and false otherwise.

Example 1
Input: board = [["C","A","T","S"],["O","R","E","P"],["D","E","N","T"]], word = "CODE"
Output: true

Explanation: Start on the top-left C, drag down to O and D, then right to E.

Example 2
Input: board = [["C","A","T","S"],["O","R","E","P"],["D","E","N","T"]], word = "RENT"
Output: true

Explanation: From R, drag right to E, down to N and right to T.

Example 3
Input: board = [["C","A","T","S"],["O","R","E","P"],["D","E","N","T"]], word = "CARD"
Output: false

Explanation: C, A and R connect, but the only D touches R diagonally.

Constraints

  • The board has between 1 and 6 rows and between 1 and 6 columns.
  • word is between 1 and 15 characters long.
  • board and word contain only English letters, uppercase or lowercase.

Follow-up: How would you find every word from a large dictionary that appears on the board, without searching for each word separately?

💡 Hint 1

Try every cell as a starting point, then explore the four neighbours recursively while matching the next letter.

💡 Hint 2

Mark a cell as used while it is on the current path and unmark it when you backtrack, so other paths can still use it.

💡 Hint 3

Cheap pruning: if the board does not contain enough copies of some letter in word, the answer is false without any search.

/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 */
function exist(board, word) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc