Word Search

Difficulty: Medium

Given a grid of letters and a word, decide whether the word can be traced by moving between adjacent cells (up, down, left or right - not diagonally), using each cell at most once.

Return true if some path spells the word, and false otherwise.

Examples

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Starting at the top-left A, you can trace A -> B -> C -> C -> E -> D moving through adjacent cells without reusing any of them.

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Starting from the S in the middle row, you can trace S -> E -> E down the right side of the grid.

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Tracing A -> B -> C reaches a C, but the only B adjacent to that C is the one already used at the start - and a cell can't be reused.

Constraints

  • 1 <= board.length, board[i].length <= 6

  • 1 <= word.length <= 15

  • board and word consist only of English letters.

Approach

The word could start anywhere, so try every cell. From a cell matching the first letter, look for a neighbor matching the second letter, then for the third among its neighbors, and so on.

Remember which cells are on the current path so none is reused. At a dead end - no unused neighbor matches the next letter - back up: free the last cell and try a different neighbor from the step before. That's backtracking: commit to a cell, explore what follows, and undo the choice when it stops working.

You can track used cells with a separate grid of true/false flags. A leaner way overwrites a used cell's letter with a placeholder while exploring from it, then restores the letter when backing out. A placeholder never matches a real letter, so it blocks reuse with no extra memory.

Solutions

Backtracking — Separate Visited Grid

Start the search from every cell. If the cell's letter matches the next letter needed, mark it visited and recursively check whether the rest of the word can be traced from an unvisited neighbor. Un-mark the cell before returning so other paths can use it.

function exist(board, word) {
  const rows = board.length;
  const cols = board[0].length;
  const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));

  function search(row, col, index) {
    if (index === word.length) return true;
    if (
      row < 0 || row >= rows ||
      col < 0 || col >= cols ||
      visited[row][col] ||
      board[row][col] !== word[index]
    ) {
      return false;
    }

    visited[row][col] = true;

    const found =
      search(row + 1, col, index + 1) ||
      search(row - 1, col, index + 1) ||
      search(row, col + 1, index + 1) ||
      search(row, col - 1, index + 1);

    visited[row][col] = false; // undo, whether or not it worked out

    return found;
  }

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      if (search(row, col, 0)) return true;
    }
  }

  return false;
}

Time: O(rows * cols * 4^L), where L is the word's length · Space: O(rows * cols) for the visited grid, plus O(L) recursion depth

Optimal — Mark In-Place Instead of a Visited Grid

Skip the visited grid. While exploring from a cell, overwrite its letter with a sentinel character (one that never appears in the word), then restore it. This saves the rows x cols grid, at the cost of briefly changing the board during the search.

function exist(board, word) {
  const rows = board.length;
  const cols = board[0].length;

  function search(row, col, index) {
    if (index === word.length) return true;
    if (
      row < 0 || row >= rows ||
      col < 0 || col >= cols ||
      board[row][col] !== word[index]
    ) {
      return false;
    }

    const original = board[row][col];
    board[row][col] = "#"; // sentinel: can never match a real letter

    const found =
      search(row + 1, col, index + 1) ||
      search(row - 1, col, index + 1) ||
      search(row, col + 1, index + 1) ||
      search(row, col - 1, index + 1);

    board[row][col] = original; // restore before returning

    return found;
  }

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      if (search(row, col, 0)) return true;
    }
  }

  return false;
}

Time: O(rows * cols * 4^L) · Space: O(L) recursion depth only - no visited grid, since the board itself is restored after use