Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Input & Output

Example 1 — Found Word
$ Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
💡 Note: Path exists: A(0,0) → B(0,1) → C(0,2) → C(1,2) → E(2,2) → D(2,1). Each step moves to adjacent cell without reusing.
Example 2 — Word Not Found
$ Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
💡 Note: Cannot form ABCB because after A(0,0) → B(0,1) → C(0,2), we need another B but the original B(0,1) cannot be reused.
Example 3 — Single Character
$ Input: board = [["A"]], word = "A"
Output: true
💡 Note: Single cell matches single character word perfectly.

Constraints

  • m == board.length
  • n = board[i].length
  • 1 ≤ m, n ≤ 6
  • 1 ≤ word.length ≤ 15
  • board and word consists of only lowercase and uppercase English letters.

Visualization

Tap to expand
Word Search - DFS Approach INPUT Character Board (3x4) A B C E S F C S A D E E Target Word: "ABCCED" Adjacent = horizontal/vertical Each cell used only once m=3 rows, n=4 cols ALGORITHM STEPS 1 Find Start Scan grid for word[0] 2 DFS Explore Check 4 neighbors 3 Mark Visited Prevent reuse 4 Backtrack Unmark on return Path Found: A B C E S F C S A D E E A--B--C--C--E--D FINAL RESULT Word found in grid! OK Output: true Path Sequence: A -- B -- C -- C E -- D (0,0)--(0,1)--(0,2)--(1,2)--(2,2)--(2,1) Time: O(m*n*4^L) Key Insight: DFS with backtracking explores all possible paths. Mark cells as visited during exploration to prevent reuse, then unmark when backtracking to allow other paths to use that cell. Early termination occurs when all characters match (return true) or bounds/mismatch (return false). TutorialsPoint - Word Search | DFS Backtracking Approach
Asked in
Microsoft 45 Amazon 38 Facebook 32 Google 28
89.2K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen