Example 1
- Input
- board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
- Output
- true
Trace A at (0,0) right to B and C, down to C, then down to E and left to D.
Given a grid of letters and a word, decide whether the word can be traced through cells that touch horizontally or vertically without reusing any cell.
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word is built from letters of sequentially adjacent cells that share a horizontal or vertical side, and no cell may be used twice within one traced word.
m == board.lengthn == board[i].length1 <= m, n <= 61 <= word.length <= 15board and word hold only English letters, upper and lower case.Trace A at (0,0) right to B and C, down to C, then down to E and left to D.
Trace S at (1,3) down to E at (2,3) and left to E at (2,2).
The second B would need a cell that is already used in the current path.
Matching is case-sensitive. The one lowercase cell does not supply the uppercase A; there is no adjacent alternative.
A matching letter is only a possible next step: its neighbors must also supply the remaining letters without reusing a cell. For Example 1, the path A, B, C, C, E, D follows six distinct cells. Keep a record of the cells in the current path, try neighbors in turn, then undo that record on return. Undoing matters even after success because the caller should receive the same board it supplied. Cells used in one failed path may be used in another.
Reveal DFS With Visited Set: intuition, complexity, and code
m times n cells can never fit and should return false at once.ABCB only pass when distinct cells supply each occurrence.board[r][c] before the bounds check, which crashes on edge cells instead of returning false.Grid path problems become graph searches by treating each cell as a node with four neighbours, and marking plus unmarking in place keeps backtracking memory tight.