Word Search

MediumBacktracking

You are given an m × n grid of letters board and a string word. Return true if word can be traced in the grid, and false otherwise.

To trace a word, start at a cell holding its first letter and move one step at a time to a horizontally or vertically adjacent cell (no diagonals) that holds the next letter. A single cell may not be used twice in the same word.

Letters are case-sensitive: "a" does not match "A". You may change board while searching, as long as you return the right answer.

Constraints

  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word contain only English letters.

Examples

Example 1

Input: board = [["S","E","E","D"],["T","A","R","S"],["O","N","E","X"]], word = "STARE"
Output: true

S (row 0) → T below it → A to the right → R → E above R. Every step moves to a neighbouring cell.

Example 2

Input: board = [["S","E","E","D"],["T","A","R","S"],["O","N","E","X"]], word = "TONES"
Output: false

T → O → N → E works, but no S touches that E, so the word can't be finished.

Example 3

Input: board = [["A","B"],["C","D"]], word = "ABA"
Output: false

The board has only one A, and a cell can't be used twice in the same word.

JavaScript you'll use: Graphs and grids in JavaScript Recursion, the call stack and memoization Strings and characters

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

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.