☰ All problems

68. Word Search

MediumBacktrackingMatrixDFS

Given an m × n grid of letters board and a string word, return true if word can be traced on the board.

A word is traced by starting at any cell and repeatedly stepping to a horizontally or vertically adjacent cell, reading one letter per cell. The same cell may not be used twice in one word. Letters are case-sensitive.

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

Explanation: Start at the top-left S, go down to O, then right to R and T.

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

Explanation: Top-right T, down to H and E, then left to N.

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

Explanation: There is only one S, and it cannot be used twice.

Constraints

  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consist of uppercase and lowercase English letters

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