AAlgoLoopSpaced repetition for LeetCode
MEDIUMBacktrackingLeetCode ↗

Word Search

The key idea

From each cell that matches the first letter, run a depth-first search that walks to adjacent cells matching the next letter, marking each visited cell so it cannot be reused, and un-marking it (backtracking) when a branch dead-ends.

Problem

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

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.

Constraints

Examples

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

Complexity

Time: O(m*n*4^L) Space: O(L)

See the full solution

410310
Step-by-step visualization
Start free →

More Backtracking problems