Typorithm · medium

Word Search

▷ Interactive algorithm labword-searchbacktrackinggrid-dfsvisited-markerchoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Word Search

0%

Backtracking

DFS from each cell, matching letters and blocking the current cell, then restoring it on the way back.

Each starting cell launches a depth-first search that follows the word letter by letter.

Marking the current cell with a placeholder prevents the same cell being reused within one path.

Restoring the letter after exploring all four directions is the undo step, freeing the cell for other paths.

Preparing algorithm lab…
01

DFS in four directions.

02

Mark the cell, then restore it.

03

Prune on bounds and mismatch.

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

  function backtrack(r, c, i) {
    if (i === word.length) return true;
    if (r < 0 || c < 0 || r >= rows || c >= cols) return false;
    if (board[r][c] !== word[i]) return false;

    const temp = board[r][c];
    board[r][c] = "#";

    const found =
      backtrack(r + 1, c, i + 1) ||
      backtrack(r - 1, c, i + 1) ||
      backtrack(r, c + 1, i + 1) ||
      backtrack(r, c - 1, i + 1);

    board[r][c] = temp;
    return found;
  }

  for (let r = 0; r < rows; r += 1) {
    for (let c = 0; c < cols; c += 1) {
      if (backtrack(r, c, 0)) return true;
    }
  }

  return false;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Word matched

Reaching the word's end means every letter matched along the path.

if (i === word.length) return true

2. Out of bounds

Stop branches that leave the board.

if (r < 0 || c < 0 || r >= rows || c >= cols) return false

3. Letter mismatch

Abandon a branch the moment the current letter does not match.

if (board[r][c] !== word[i]) return false

4. Mark visited

Temporarily block this cell so the path cannot reuse it.

board[r][c] = "#"

5. Restore (undo)

Put the letter back so other paths can use this cell.

board[r][c] = temp

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Word Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn