Given an m×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 (horizontally or vertically). The same letter cell may not be used more than once.
board=[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word="ABCCED"trueword="SEE"trueword="ABCB"falseboard[r][c] == word[0], launch DFS from itk == word.length → full match, return truefalsefalseWe explore every possible path depth-first. Marking the current cell as visited ('#') prevents revisiting it in the same path. When we backtrack (restore the cell), that cell becomes available again for other paths — ensuring correctness without extra space for a visited array.
Listing every path in the grid is exponential and wasteful. We only need to follow paths that keep matching the word.
Try each cell as a starting point. From a cell that matches the current letter, explore its four neighbours for the next letter. Mark the cell as used while exploring, and unmark it when you come back, which is backtracking.
DFS plus mark and unmark is backtracking on a grid. Stop early as soon as a letter does not match.
Run the animation above on your own input, or watch the 1:26 video explanation of Word Search with a dry run and Java code.