1. Word matched
Reaching the word's end means every letter matched along the path.
if (i === word.length) return trueTyporithm · medium
Step 1 of 8 · intro card
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.
DFS in four directions.
Mark the cell, then restore it.
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;
}Connect each part of the code to the concept before you type.
Reaching the word's end means every letter matched along the path.
if (i === word.length) return trueStop branches that leave the board.
if (r < 0 || c < 0 || r >= rows || c >= cols) return falseAbandon a branch the moment the current letter does not match.
if (board[r][c] !== word[i]) return falseTemporarily block this cell so the path cannot reuse it.
board[r][c] = "#"Put the letter back so other paths can use this cell.
board[r][c] = tempRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputBoard ABCE / SFCS / ADEE · word ABCCED
Follow temporary values, local state and supporting structures at this step.
Matched prefix0 entries
Local state · indices and saved values
Input · not auxiliary memory
Target word6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state