Word Search
Determine if a word exists in a 2D character grid by tracing adjacent cells with depth-first search and in-place backtracking.
01The problem
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 | Why |
|---|---|---|
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" | true | Path: (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (2,1) |
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" | true | Path found on lower rows |
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" | false | Cell (0,1) cannot be reused |
Constraints: m == board.length, n == board[i].length, 1 <= m, n <= 6, 1 <= word.length <= 15. Letters are lowercase and uppercase English.
Loading the rest of the lesson…