Word Search Visualizer & Step-by-Step Algorithm Solution

Determine if a target word exists in a 2D grid of characters by constructing a path of adjacent cells without reusing any cell.

Category: backtracking | Difficulty: Medium

Tags: Backtracking, Matrix, DFS, Recursion

Word Search

Board (3x4)
0
1
2
3
0
1
2
A
B
C
E
S
F
C
S
A
D
E
E
Active Cell
Active Row / Col / Box
Conflict / Subtracted
Highlighted / Subgrid
Target Word
index
A
0
B
1
C
2
C
3
E
4
D
5
100%
state
m3
n4
wordABCCED
Initialization
1/52
Explanation

Start Word Search for "ABCCED" on 3x4 grid.

Source Code
1function exist(board: string[][], word: string): boolean {
2 const m = board.length;
3 const n = board[0].length;
4
5 function dfs(row: number, col: number, index: number): boolean {
6 if (index === word.length) return true;
7 if (row < 0 || row >= m || col < 0 || col >= n) return false;
8 if (board[row][col] !== word[index]) return false;
9
10 const temp = board[row][col];
11 board[row][col] = "#";
12
13 const found =
14 dfs(row + 1, col, index + 1) ||
15 dfs(row - 1, col, index + 1) ||
16 dfs(row, col + 1, index + 1) ||
17 dfs(row, col - 1, index + 1);
18
19 board[row][col] = temp;
20 return found;
21 }
22
23 for (let r = 0; r < m; r++) {
24 for (let c = 0; c < n; c++) {
25 if (dfs(r, c, 0)) return true;
26 }
27 }
28
29 return false;
30}