{"id":"word-search","title":"Word Search","difficulty":"medium","patterns":["backtracking"],"primaryConcept":"string-grid-search","concepts":["string-grid-search","graph-grid-fill","backtracking-constraint-placement"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"board","sizeMetric":"matrix-cells","sizes":[4,9,16],"alphabet":"ABCD","secondaryParams":{"word":{"strategy":"fixed","value":"ABCD"}},"constraints":["path-search","boolean-output"]},"description":"Given an `m x n` grid of characters `board` and a string `word`, return `true` if `word` exists in the grid.\n\nThe word must be built from sequentially adjacent cells, where adjacent cells share a side horizontally or vertically. A cell may be used at most once in the same word path.","examples":[{"input":"board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"","output":"true","explanation":"The path A -> B -> C -> C -> E -> D uses adjacent cells without reusing one."},{"input":"board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"","output":"true","explanation":"The word can be traced down the right side of the board."},{"input":"board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"","output":"false","explanation":"The last B would require reusing an already used cell."}],"constraints":[{"id":"m-len-board","text":"m == len(board)"},{"id":"n-len-board-i","text":"n == len(board[i])"},{"id":"1-m-n-6","text":"1 <= m, n <= 6","check":[{"kind":"sizeRange","target":"board","measure":"matrixRows","min":1,"max":6},{"kind":"valueRange","target":"board","selector":"arrayItemLengths","min":1,"max":6}]},{"id":"1-len-word-15","text":"1 <= len(word) <= 15","check":{"kind":"sizeRange","target":"word","measure":"stringLength","min":1,"max":15}},{"id":"board-i-j-and-word-contain-uppercase-or-lowercase-english-letter","text":"board[i][j] and word contain uppercase or lowercase English letters","check":[{"kind":"domain","target":"board","selector":"gridCells","allowed":["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]},{"kind":"domain","target":"word","selector":"stringChars","allowed":["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}]}],"starterCode":"class Solution:\n    def exist(self, board: list[list[str]], word: str) -> bool:\n        # Your code here\n        pass","functionName":"exist","testCases":[{"id":"1","input":{"board":[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"word":"ABCCED"},"expected":true,"description":"Canonical true path with a turn."},{"id":"2","input":{"board":[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"word":"SEE"},"expected":true,"description":"Starts away from the top-left cell."},{"id":"3","input":{"board":[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"word":"ABCB"},"expected":false,"description":"Would need to reuse a cell."},{"id":"4","input":{"board":[["a"]],"word":"a"},"expected":true,"description":"Single-cell success."},{"id":"5","input":{"board":[["a"]],"word":"b"},"expected":false,"description":"Single-cell mismatch."},{"id":"6","input":{"board":[["A","A"],["A","A"]],"word":"AAAA"},"expected":true,"description":"Uses every cell once."},{"id":"7","input":{"board":[["A","A"],["A","A"]],"word":"AAAAA"},"expected":false,"description":"The word is longer than the number of cells."},{"id":"h1","input":{"board":[["C","A","A"],["A","A","A"],["B","C","D"]],"word":"AAB"},"expected":true,"description":"Requires choosing the branch that reaches B."},{"id":"h2","input":{"board":[["a","b"],["c","d"]],"word":"abcd"},"expected":false,"description":"Diagonal movement is not allowed."},{"id":"h3","input":{"board":[["A","A","B"],["B","A","A"],["A","B","A"]],"word":"AABAA"},"expected":true,"description":"The search must follow a winding path through repeated letters."},{"id":"topup-lowercase-turning-path","input":{"board":[["a","b","c"],["h","g","d"],["i","f","e"]],"word":"abcdefg"},"expected":true,"description":"Lowercase path turns through adjacent cells without reuse."},{"id":"topup-diagonal-not-allowed","input":{"board":[["A","X"],["X","B"]],"word":"AB"},"expected":false,"description":"Diagonal adjacency is not enough to form a word path."}],"hints":[{"level":1,"content":"Try each cell as the first character of the word.","revealPattern":false},{"level":2,"content":"Use DFS from a matching cell and carry the index of the next character to match.","revealPattern":true},{"level":3,"content":"Temporarily mark the current cell as visited before exploring neighbors, then restore it when backtracking returns.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-with-separate-visited","name":"DFS with a separate visited matrix","summary":"Keep the board unchanged and mark the cells currently on the path in a separate visited grid.","decisionReason":"It carries a separate visited set alongside the board, using extra space when the board itself can record the path.","complexity":{"time":"O(m*n*4^L)","space":"O(m*n)"},"tradeoffs":["Easier to reason about because board letters are never overwritten, but it carries an additional matrix."],"isOptimal":false},{"id":"dfs-with-backtracking","name":"DFS with visited marking","summary":"Start from each matching cell, recursively match the next character, and restore cells after each path.","decisionReason":"Mark each cell as you step onto it and restore it as you leave, so the board itself records the path with no extra space.","complexity":{"time":"O(m*n*4^L)","space":"O(L)"},"tradeoffs":["Runs in O(m*n*4^L) time and uses O(L) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"scan-grid","title":"Try every starting cell","description":"Use nested loops so every board coordinate can be considered as a word start.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"semanticSpec":{"intent":"Traverse the full grid as possible DFS entry points.","doneWhen":"The code has nested row and column iteration over the board dimensions.","shouldFailWhen":"Only one fixed start cell is checked.","roles":["row cursor","column cursor"],"mustProve":["nested grid traversal"],"mustNotAccept":["single-cell probing"],"proofSnippets":[{"id":"py-word-search-scan-grid","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]"}]},"hint":"Use the nested grid scan so every coordinate can become a possible launch point."},{"id":"match-target-cell","title":"Reject invalid DFS cells","description":"Stop a DFS branch when it leaves the board or the current cell does not match the current word character.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"matches_target_cell_before_exploration","scope":"match-target-cell","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Guard recursive exploration by comparing the current grid cell to the target character for this depth.","doneWhen":"The DFS helper checks bounds and compares board[row][col] with the indexed word character before recursing.","shouldFailWhen":"The helper checks only bounds or only a hard-coded visited marker.","roles":["current cell","word index"],"mustProve":["current cell target guard"],"mustNotAccept":["bounds-only DFS"],"proofSnippets":[{"id":"py-word-search-match-target","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        return True"}]},"hint":"Use the depth or index parameter to decide which character the current cell must match."},{"id":"mark-visited","title":"Mark and restore visited cells","description":"Temporarily mark the current cell before exploring and restore it after every unsuccessful recursive branch.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"marks_visited_and_restores_cell","scope":"mark-visited","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Prevent one path from reusing a cell while still allowing other paths to use it later.","doneWhen":"The helper saves the current cell, writes a visited marker, recurses, and writes the saved value back before returning false or propagating success.","shouldFailWhen":"The code marks a cell but fails to restore it after an unsuccessful path.","roles":["visited marker","saved cell"],"mustProve":["temporary cell mutation","cell restoration"],"mustNotAccept":["permanent board mutation"],"proofSnippets":[{"id":"py-word-search-mark-visited","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        dfs(r + 1, c, index + 1)\n        board[r][c] = temp"}]},"hint":"A failed branch must leave the board exactly as it found it for the next route."},{"id":"explore-neighbors","title":"Explore four directions","description":"Recurse to each orthogonal neighbor with the next word index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Continue the search through all four side-adjacent cells.","doneWhen":"The DFS helper calls itself for row + 1, row - 1, col + 1, and col - 1.","shouldFailWhen":"The helper explores only one direction or includes diagonal movement instead.","roles":["row cursor","column cursor","word index"],"mustProve":["four orthogonal recursive calls"],"mustNotAccept":["single-direction recursion"],"proofSnippets":[{"id":"py-word-search-explore-neighbors","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found"}]},"hint":"Each recursive call should keep one coordinate fixed and move the other by one."},{"id":"start-search","title":"Launch DFS from the grid","description":"Call the DFS helper from matching start cells and return true as soon as a full path is found.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_grid_search_from_every_cell","scope":"start-search","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Connect the outer grid scan to the recursive search helper.","doneWhen":"Nested grid loops call the recursive helper with the current row and column.","shouldFailWhen":"The helper is defined but never launched from the board scan.","roles":["grid scan","recursive helper"],"mustProve":["recursive search kickoff from grid coordinates"],"mustNotAccept":["unreachable helper"],"proofSnippets":[{"id":"py-word-search-start-search","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    found_word = False\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                found_word = True"}]},"hint":"The outer loops find possible starts; DFS verifies whether one of those starts completes the word."},{"id":"accept-full-word-match","title":"Accept a completed word path","description":"Return true as soon as the recursive search has matched every character in the word.","commonMistakes":["Continuing to explore neighbors after the whole word is already matched","Returning false after matching the last character"],"hint":"The success base case is about the word index or last matched character, not about finding another neighbor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_grid_search_from_every_cell","scope":"success-base-case","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Recognize terminal success for the recursive word path.","doneWhen":"This step is done when the DFS returns true once all characters have been matched and that true result short-circuits back to the caller.","shouldFailWhen":"This step should fail if the helper keeps searching after the word is complete or loses a successful branch result.","roles":["word index","matched path","success return","short-circuit"],"mustProve":["The helper detects that the full word has been matched.","A successful recursive branch returns true.","The outer search stops once a true branch is found."],"mustNotAccept":["Only returning true for a fixed coordinate.","Ignoring a true recursive result."],"proofSnippets":[{"id":"py-word-search-accept-full-word-match","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        if index == len(word) - 1:\n            return True\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    found_word = False\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                found_word = True"}],"equivalentVariants":["Return true when index equals word length.","Return true when the current cell matches the final character."]}},{"id":"return-found","title":"Return the search verdict","description":"Return true when any DFS launch finds the word, and return false only after every start cell has been tried.","commonMistakes":["Returning true without checking the DFS result","Returning false before all start cells have been tried","Forgetting the final false return when no path exists"],"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"returns_grid_search_verdict","scope":"return-found","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Connect the DFS search result to the top-level boolean answer.","doneWhen":"The grid scan returns true from a successful recursive search and returns false after the scan finishes without a match.","shouldFailWhen":"The function omits either the successful early return or the final no-match false return.","roles":["grid scan","recursive helper","success return","failure return"],"mustProve":["A recursive search success returns true from the outer function.","The outer function returns false only after the grid launch scan has no successful path."],"mustNotAccept":["Only proving the helper's success base case.","Only returning true without a final false fallback."],"proofSnippets":[{"id":"py-word-search-return-found","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        if index == len(word) - 1:\n            return True\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                return True\n    return False"}]}}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Trace a word through neighboring cells","workspacePanel":"problem","body":["Decide whether a word can be spelled by stepping through the grid, moving only between side-by-side cells (up, down, left, right) and never reusing a cell.","In this 2x2 board, \"AAB\" can be traced: the top-right A, to the top-left A, down to the B. So the answer is true."]},{"id":"where-start","kind":"case-probe","chapter":"The idea","eyebrow":"Find the launch points","title":"Where can a word search start?","workspacePanel":"visualizer","summary":"word = \"AAB\" on the 2x2 board shown here.","options":[{"id":"first-letter","label":"From every cell whose letter equals the first letter of the word","rationale":"Any matching cell could be the start of the path, so the search has to try a depth-first walk from each of them until one spells the word.","isCorrect":true},{"id":"top-left","label":"Always from the top-left cell","rationale":"The word might not pass through the top-left at all; every cell matching the first letter is a candidate start."},{"id":"corners","label":"From the four corners","rationale":"There is nothing special about corners; the launch points are wherever the first letter appears."}],"answer":"From every cell equal to the first letter. Each is a possible start, so the search tries a walk from each until one succeeds.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-state","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"r":0,"c":0,"labels":{"grid":"board"}}}]}},{"id":"no-reuse","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"As the path extends, how do you keep from stepping on a cell twice?","workspacePanel":"visualizer","summary":"You have just matched a cell and are about to explore its neighbors.","options":[{"id":"mark","label":"Mark the current cell as visited before exploring its neighbors","rationale":"Flagging the cell while its sub-walk runs means a deeper step can never wander back onto it, so the path stays simple.","isCorrect":true},{"id":"sort","label":"Remember the letters used so far","rationale":"Letters repeat across cells; you must block the specific cell, not its letter, from being reused."},{"id":"length","label":"Stop once the path is as long as the grid","rationale":"Length is not the issue; a single cell could still be revisited within a shorter path unless it is marked."}],"answer":"Mark the cell visited before recursing. While its sub-walk runs the cell is off-limits, so the path can never step on it twice.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mark-state","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,1]],"changed":[],"r":0,"c":1,"labels":{"grid":"board"}}}]}},{"id":"restore","kind":"case-probe","chapter":"The idea","eyebrow":"Find the key rule","title":"When a walk dead-ends and the search backs out of a cell, what happens to its mark?","workspacePanel":"visualizer","summary":"A branch failed and the search is backing out of the marked cell.","options":[{"id":"restore","label":"Restore the cell: clear its visited mark so other walks can use it","rationale":"The cell was only blocked for the path that just failed; a different start or branch may legitimately need to pass through it, so leaving as you found it is essential.","isCorrect":true},{"id":"keep","label":"Leave it marked, it was already tried","rationale":"Leaving it marked blocks every later path through that cell, so a word that really exists can be missed."},{"id":"reset-all","label":"Clear the whole board","rationale":"Only the cell being left should be restored; the cells still on the active path must stay marked."}],"answer":"Restore it. The mark only protected the failed walk, so clearing it on the way out frees the cell for any other path that needs it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"restore-state","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"r":0,"c":1,"labels":{"grid":"board"}}}]}},{"id":"search-cost","kind":"case-probe","chapter":"The idea","eyebrow":"Count the work","title":"How much work can this search do in the worst case?","workspacePanel":"visualizer","summary":"Every cell can be a start, and each step of a length-L word picks among the neighbors.","options":[{"id":"branching","label":"Up to m*n starts, and each of the L steps fans out to its neighbors, so the work grows like m*n*4^L","rationale":"Each of the m*n cells can launch a walk, and a length-L walk tries up to four directions at every step, so the branches multiply to about 4^L per start.","isCorrect":true},{"id":"linear","label":"About m*n, since each cell is visited once","rationale":"A single scan would be m*n, but each start launches a branching walk that can revisit cells across different paths, so the cost is far above linear."},{"id":"squared","label":"About (m*n) squared, one pass per starting cell","rationale":"The walk from each start branches up to four ways per step, so the word length L drives the exponential part of the cost."}],"answer":"Up to m*n starts, and each of the L steps branches through its neighbors, so the work grows like m*n*4^L in the worst case.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cost-state","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,0]],"changed":[],"r":0,"c":0,"labels":{"grid":"board"}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,1]],"changed":[],"r":0,"c":1,"labels":{"grid":"board"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Step on, explore, step off","workspacePanel":"visualizer","body":["From a starting cell, mark it and look in the four neighbors for the next letter. Follow a match deeper; on a dead end, restore the cells you marked and back up to try another route.","Watch \"AAB\" fail from the top-left start, get fully restored, and then succeed from the top-right."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"r":0,"c":0,"labels":{"grid":"board"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Walk the grid","title":"Search for \"AAB\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-tl","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,0]],"changed":[[0,0]],"r":0,"c":0,"labels":{"grid":"board"}}},{"id":"extend","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,0],[0,1]],"changed":[[0,1]],"r":0,"c":1,"labels":{"grid":"board"}}},{"id":"dead-end","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,0],[0,1]],"changed":[],"r":0,"c":1,"labels":{"grid":"board"}}},{"id":"restore","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"labels":{"grid":"board"}}},{"id":"success","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,1],[0,0],[1,0]],"changed":[[0,1],[0,0],[1,0]],"r":1,"c":0,"labels":{"grid":"board"}}}]},"beats":[{"id":"start-tl","title":"The top-left A matches the first letter. What does the walk do next?","prompt":"board[0][0] is A.","options":[{"id":"mark-look","label":"Mark it visited, then look in its neighbors for the next A","rationale":"A match means step onto the cell: mark it so the walk cannot return, then search the neighbors for the second letter.","isCorrect":true},{"id":"record","label":"Record it as the answer","rationale":"One matched letter is not the whole word; the search must keep extending before it can succeed."},{"id":"skip","label":"Skip to the next start","rationale":"It matched the first letter, so this is a live branch to explore, not one to skip."}],"answer":"Mark it and look around. The cell is flagged visited, and the search scans its neighbors for the next letter, A."},{"id":"extend","title":"The walk steps to neighbor (0,1), also A. What is the path state now?","prompt":"The next target letter is B.","options":[{"id":"two","label":"(0,0) then (0,1), both marked, now looking for B","rationale":"The second A extends the path, so both top cells are marked visited and the search looks in (0,1)’s neighbors for the final letter, B.","isCorrect":true},{"id":"reset","label":"Only (0,1) is marked now","rationale":"(0,0) stays marked while its sub-walk runs; both cells are on the active path."},{"id":"done","label":"The word is found","rationale":"Only two of three letters are matched; the search still needs a B."}],"answer":"(0,0) and (0,1) are both marked, and the search now looks for B among (0,1)’s neighbors."},{"id":"dead-end","title":"From (0,1), the only unvisited neighbor is (1,1) = A. What happens to this branch?","prompt":"The word still needs a B; (0,0) is already marked.","options":[{"id":"dead","label":"This branch dead-ends; there is no B reachable from here","rationale":"(0,1)’s unvisited neighbor is an A, and B is needed, so no continuation works and the walk from the top-left A has failed.","isCorrect":true},{"id":"use-visited","label":"Step back onto (0,0)","rationale":"(0,0) is marked visited, so the path cannot reuse it; that is exactly what the mark prevents."},{"id":"wrong","label":"It still works somehow","rationale":"There is no unvisited B beside (0,1), so this branch cannot spell AAB."}],"answer":"It dead-ends. The only unvisited neighbor is A while the word needs B, so the top-left start fails."},{"id":"restore","title":"The whole top-left branch failed. What happens to (0,0) and (0,1) now?","prompt":"The search is backing all the way out of this start.","options":[{"id":"restore-both","label":"Both are restored, so the board is clean for the next start to try","rationale":"Each cell is unmarked as the search leaves it, so the failed walk leaves no trace and the cells are free for any other path.","isCorrect":true},{"id":"keep","label":"They stay marked, the start was already tried","rationale":"Leaving them marked would block the real path, which actually runs through both of these cells from a different start."},{"id":"half","label":"Only (0,1) is restored","rationale":"Every cell on the failed walk is restored, including (0,0); none stays marked once its branch is abandoned."}],"answer":"Both are restored. The failed walk unmarks every cell it touched, leaving the board clean for the next start."},{"id":"success","title":"The search restarts from the next A at (0,1). What does this walk return?","prompt":"(0,0) and (0,1) are clear again; B sits at (1,0).","options":[{"id":"true","label":"It spells A, A, B and returns true, using the very cells the first walk had marked","rationale":"Because the failed branch restored (0,0) and (0,1), this start can pass through them, reach the B, and complete the word.","isCorrect":true},{"id":"blocked","label":"It is blocked, those cells were used before","rationale":"They were restored after the first failure, so they are available again; that is the whole point of restoring."},{"id":"false","label":"It returns false","rationale":"The path (0,1) to (0,0) to (1,0) spells AAB with no reuse, so the search returns true."}],"answer":"True. The restored cells let this start walk (0,1) to (0,0) to (1,0), spelling AAB, which is why restoring mattered."}]},{"id":"no-restore-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could the walk just step to any touching cell?","summary":"Letting a step move to all eight surrounding cells looks like a tidy way to reach every neighbor, and it passes the boards where the answer happens to sit straight up, down, or sideways. But the problem only counts cells that share a side. Watch it judge a board where the letters touch only at a corner.","pitfall":"The code below recurses into all eight surrounding cells, so a diagonal step counts as a legal move.","whyItMatters":"On board [[\"A\",\"X\"],[\"X\",\"B\"]] with word \"AB\", the A and the B touch only at a corner, so no side-adjacent path spells the word and the answer is false. Allowing the diagonal step lets the walk jump straight from A to B and return true, a word the board does not actually contain. Restrict the recursion to the four side neighbors so every step preserves shared-edge adjacency.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def exist(board: list[list[str]], word: str) -> bool:\n    rows = len(board)\n    cols = len(board[0])\n\n    def dfs(r: int, c: int, index: int) -> bool:\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        if index == len(word) - 1:\n            return True\n        temp = board[r][c]\n        board[r][c] = \"#\"\n        found = False\n        for dr in (-1, 0, 1):\n            for dc in (-1, 0, 1):\n                found = found or dfs(r + dr, c + dc, index + 1)\n        board[r][c] = temp\n        return found\n\n    for r in range(rows):\n        for c in range(cols):\n            if dfs(r, c, 0):\n                return True\n    return False","steps":[{"id":"mark","title":"The walk starts on A at (0,0) and marks it","codeLine":11,"summary":"A matches the first letter, so the cell is marked and the walk looks for B.","state":{"grid":[["A","X"],["X","B"]],"filled":[[0,0]],"changed":[[0,0]],"r":0,"c":0,"labels":{"grid":"board"}}},{"id":"diagonal","title":"The loop also recurses into the corner cell (1,1)","codeLine":15,"summary":"Because dr and dc both range over -1, 0, 1, the walk steps diagonally onto (1,1), which holds B.","state":{"grid":[["A","X"],["X","B"]],"filled":[[0,0],[1,1]],"changed":[[1,1]],"r":1,"c":1,"labels":{"grid":"board"}}},{"id":"wrong-true","title":"B is the last letter, so the search reports true","codeLine":9,"summary":"The diagonal hop matched the final letter, so the buggy walk returns true for a word with no side-adjacent path.","state":{"grid":[["A","X"],["X","B"]],"filled":[[0,0],[1,1]],"changed":[],"r":1,"c":1,"labels":{"grid":"board"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = board.length;\nconst cols = board[0].length;\nfunction dfs(r, c, index) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[index]) {\n        return false;\n    }\n    if (index == (word.length - 1)) {\n        return true;\n    }\n    const temp = board[r][c];\n    board[r][c] = \"#\";\n    let found = false;\n    for (const dr of [-1, 0, 1]) {\n        for (const dc of [-1, 0, 1]) {\n            found = found || dfs((r + dr), (c + dc), (index + 1));\n        }\n    }\n    board[r][c] = temp;\n    return found;\n}\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (dfs(r, c, 0)) {\n            return true;\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":18,"17":19,"19":21,"20":22,"21":23,"22":24,"23":28},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":9},"15":{"startLine":15,"endLine":17},"17":{"startLine":19,"endLine":20},"22":{"startLine":24,"endLine":27}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = board.length;\nconst cols = board[0].length;\nfunction dfs(r: number, c: number, index: number): boolean {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[index]) {\n        return false;\n    }\n    if (index == (word.length - 1)) {\n        return true;\n    }\n    const temp = board[r][c];\n    board[r][c] = \"#\";\n    let found = false;\n    for (const dr of [-1, 0, 1]) {\n        for (const dc of [-1, 0, 1]) {\n            found = found || dfs((r + dr), (c + dc), (index + 1));\n        }\n    }\n    board[r][c] = temp;\n    return found;\n}\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (dfs(r, c, 0)) {\n            return true;\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":18,"17":19,"19":21,"20":22,"21":23,"22":24,"23":28},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":9},"15":{"startLine":15,"endLine":17},"17":{"startLine":19,"endLine":20},"22":{"startLine":24,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = board.Count;\nint cols = board[0].Count;\nbool Dfs(int r, int c, int index) {\n    if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[index].ToString()) {\n        return false;\n    }\n    if (index == word.Length - 1) {\n        return true;\n    }\n    string temp = board[r][c];\n    board[r][c] = \"#\";\n    bool found = false;\n    foreach (int dr in new List<int> { -1, 0, 1 }) {\n        foreach (int dc in new List<int> { -1, 0, 1 }) {\n            found = found || Dfs(r + dr, c + dc, index + 1);\n        }\n    }\n    board[r][c] = temp;\n    return found;\n    return false;\n}\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (Dfs(r, c, 0)) {\n            return true;\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":18,"17":19,"19":22,"20":23,"21":24,"22":25,"23":29},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":6},"9":{"startLine":8,"endLine":9},"15":{"startLine":15,"endLine":17},"17":{"startLine":19,"endLine":21},"22":{"startLine":25,"endLine":28}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<bool(int, int, int)> dfs;\n\nint rows = board.size();\nint cols = board[0].size();\ndfs = [&]( int r, int c, int index ) -> bool {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || board[r][c] != string(1, word[index]))) {\n        return false;\n    }\n    if (index == (word.size() - 1)) {\n        return true;\n    }\n    string temp = board[r][c];\n    board[r][c] = \"#\";\n    bool found = false;\n    for (int dr : vector<int>{-1, 0, 1}) {\n        for (int dc : vector<int>{-1, 0, 1}) {\n            found = found || dfs((r + dr), (c + dc), (index + 1));\n        }\n    }\n    board[r][c] = temp;\n    return found;\n};\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (dfs(r, c, 0)) {\n            return true;\n        }\n    }\n}\nreturn false;","lineMap":{"2":3,"3":4,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":20,"17":21,"19":23,"20":24,"21":25,"22":26,"23":30},"statementBundles":{"3":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"15":{"startLine":17,"endLine":19},"17":{"startLine":21,"endLine":22},"22":{"startLine":26,"endLine":29}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean dfs(int r, int c, int index, int rows, int cols, List<List<String>> board, String word) {\n    if (((((r < 0 || r >= rows) || c < 0) || c >= cols) || !String.valueOf(word.charAt(index)).equals(board.get(r).get(c)))) {\n        return false;\n    }\n    if (index == (word.length() - 1)) {\n        return true;\n    }\n    String temp = board.get(r).get(c);\n    board.get(r).set(c, \"#\");\n    boolean found = false;\n    for (Integer dr : new ArrayList<>(List.of(-1, 0, 1))) {\n        for (Integer dc : new ArrayList<>(List.of(-1, 0, 1))) {\n            found = found || dfs((r + dr), (c + dc), (index + 1), rows, cols, board, word);\n        }\n    }\n    board.get(r).set(c, temp);\n    return found;\n}\n\nint rows = board.size();\nint cols = board.get(0).size();\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (dfs(r, c, 0, rows, cols, board, word)) {\n            return true;\n        }\n    }\n}","lineMap":{"2":20,"3":21,"6":2,"7":3,"8":5,"9":6,"10":8,"11":9,"12":10,"13":11,"14":12,"15":13,"16":16,"17":17,"19":22,"20":23,"21":24,"22":25},"statementBundles":{"7":{"startLine":3,"endLine":4},"9":{"startLine":6,"endLine":7},"15":{"startLine":13,"endLine":15},"17":{"startLine":17,"endLine":18},"22":{"startLine":25,"endLine":28}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The mark-and-restore walk found AAB even though its first start failed. Now stress the boundaries, where the constraints push back hardest.","Two inputs are worth a look: a word whose first letter appears nowhere on the board, and a word longer than the number of cells on the board."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"r":0,"c":0,"labels":{"grid":"board"}}}]}},{"id":"missing-letter-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"The word starts with a letter that is nowhere on the board. What happens?","workspacePanel":"visualizer","summary":"The word starts with C on this A/A/B/A board.","options":[{"id":"false-fast","label":"The search returns false without ever stepping onto a cell","rationale":"The outer scan finds no cell equal to the first letter, so no walk is ever launched and the answer is false immediately.","isCorrect":true},{"id":"crash","label":"It fails trying to start","rationale":"The scan simply finds no starting cell and falls through to false; there is nothing to crash on."},{"id":"true","label":"It still finds the word","rationale":"If the first letter is absent, the word cannot begin anywhere, so it cannot be present."}],"answer":"False, with no walk launched. If no cell matches the first letter, there is nowhere to begin, so the word cannot be on the board.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"missing-state","state":{"grid":[["A","A"],["B","A"]],"filled":[],"changed":[],"labels":{"grid":"board"}}}]}},{"id":"too-long-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"The word is longer than the number of cells. Can it ever be found?","workspacePanel":"visualizer","summary":"A 2x2 board, a five-letter word.","options":[{"id":"never","label":"Never; with no cell reused, a path can be at most as long as the board has cells","rationale":"Each step uses a fresh cell, so the longest possible path equals the cell count; a longer word must run out of cells and every walk dead-ends.","isCorrect":true},{"id":"maybe","label":"Sometimes, if letters repeat","rationale":"Repeated letters do not help; the path still cannot reuse a cell, so it cannot exceed the cell count in length."},{"id":"wrap","label":"Yes, by wrapping around","rationale":"There is no wrapping; moves are only to side-by-side cells, and each cell is used once."}],"answer":"Never. Without reuse, a path is capped at the number of cells, so any word longer than that cannot fit and every walk dead-ends.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"too-long-state","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,0],[0,1],[1,0],[1,1]],"changed":[],"r":1,"c":1,"labels":{"grid":"board"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Mark on the way in, restore on the way out.","body":["Launch a walk from every cell matching the first letter. At each step, match the current letter, mark the cell so the walk cannot reuse it, and recurse into the four neighbors for the next letter.","When a branch finishes or dead-ends, restore the cell before returning, so the board is left clean for the next path; the word is found when the last letter matches."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[["A","A"],["B","A"]],"filled":[[0,1],[0,0]],"changed":[],"r":1,"c":0,"labels":{"grid":"board"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the grid backtracking","eyebrow":"Code the rule","summary":"The code scans every possible start, rejects out-of-bounds or mismatched cells, marks the active path, explores four neighbors, restores on the way out, and returns the first successful search.","workspacePanel":"code","checkpoints":[{"id":"scan-grid","title":"Try every starting cell","description":"Use nested loops so every board coordinate can be considered as a word start.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-enumeration","fact":"traverses_nested_grid","scope":"nested-loops","readMode":"grid-enumeration-value-query-v1"}]},"semanticSpec":{"intent":"Traverse the full grid as possible DFS entry points.","doneWhen":"The code has nested row and column iteration over the board dimensions.","shouldFailWhen":"Only one fixed start cell is checked.","roles":["row cursor","column cursor"],"mustProve":["nested grid traversal"],"mustNotAccept":["single-cell probing"],"proofSnippets":[{"id":"py-word-search-scan-grid","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]"}]},"hint":"Use the nested grid scan so every coordinate can become a possible launch point."},{"id":"match-target-cell","title":"Reject invalid DFS cells","description":"Stop a DFS branch when it leaves the board or the current cell does not match the current word character.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"matches_target_cell_before_exploration","scope":"match-target-cell","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Guard recursive exploration by comparing the current grid cell to the target character for this depth.","doneWhen":"The DFS helper checks bounds and compares board[row][col] with the indexed word character before recursing.","shouldFailWhen":"The helper checks only bounds or only a hard-coded visited marker.","roles":["current cell","word index"],"mustProve":["current cell target guard"],"mustNotAccept":["bounds-only DFS"],"proofSnippets":[{"id":"py-word-search-match-target","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        return True"}]},"hint":"Use the depth or index parameter to decide which character the current cell must match."},{"id":"mark-visited","title":"Mark and restore visited cells","description":"Temporarily mark the current cell before exploring and restore it after every unsuccessful recursive branch.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"marks_visited_and_restores_cell","scope":"mark-visited","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Prevent one path from reusing a cell while still allowing other paths to use it later.","doneWhen":"The helper saves the current cell, writes a visited marker, recurses, and writes the saved value back before returning false or propagating success.","shouldFailWhen":"The code marks a cell but fails to restore it after an unsuccessful path.","roles":["visited marker","saved cell"],"mustProve":["temporary cell mutation","cell restoration"],"mustNotAccept":["permanent board mutation"],"proofSnippets":[{"id":"py-word-search-mark-visited","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        dfs(r + 1, c, index + 1)\n        board[r][c] = temp"}]},"hint":"A failed branch must leave the board exactly as it found it for the next route."},{"id":"explore-neighbors","title":"Explore four directions","description":"Recurse to each orthogonal neighbor with the next word index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"explores_grid_neighbors","scope":"explore-neighbors","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Continue the search through all four side-adjacent cells.","doneWhen":"The DFS helper calls itself for row + 1, row - 1, col + 1, and col - 1.","shouldFailWhen":"The helper explores only one direction or includes diagonal movement instead.","roles":["row cursor","column cursor","word index"],"mustProve":["four orthogonal recursive calls"],"mustNotAccept":["single-direction recursion"],"proofSnippets":[{"id":"py-word-search-explore-neighbors","language":"python","code":"def exist(board, word):\n    for r in range(len(board)):\n        for c in range(len(board[0])):\n            cell = board[r][c]\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found"}]},"hint":"Each recursive call should keep one coordinate fixed and move the other by one."},{"id":"start-search","title":"Launch DFS from the grid","description":"Call the DFS helper from matching start cells and return true as soon as a full path is found.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_grid_search_from_every_cell","scope":"start-search","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Connect the outer grid scan to the recursive search helper.","doneWhen":"Nested grid loops call the recursive helper with the current row and column.","shouldFailWhen":"The helper is defined but never launched from the board scan.","roles":["grid scan","recursive helper"],"mustProve":["recursive search kickoff from grid coordinates"],"mustNotAccept":["unreachable helper"],"proofSnippets":[{"id":"py-word-search-start-search","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    found_word = False\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                found_word = True"}]},"hint":"The outer loops find possible starts; DFS verifies whether one of those starts completes the word."},{"id":"accept-full-word-match","title":"Accept a completed word path","description":"Return true as soon as the recursive search has matched every character in the word.","commonMistakes":["Continuing to explore neighbors after the whole word is already matched","Returning false after matching the last character"],"hint":"The success base case is about the word index or last matched character, not about finding another neighbor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"starts_grid_search_from_every_cell","scope":"success-base-case","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Recognize terminal success for the recursive word path.","doneWhen":"This step is done when the DFS returns true once all characters have been matched and that true result short-circuits back to the caller.","shouldFailWhen":"This step should fail if the helper keeps searching after the word is complete or loses a successful branch result.","roles":["word index","matched path","success return","short-circuit"],"mustProve":["The helper detects that the full word has been matched.","A successful recursive branch returns true.","The outer search stops once a true branch is found."],"mustNotAccept":["Only returning true for a fixed coordinate.","Ignoring a true recursive result."],"proofSnippets":[{"id":"py-word-search-accept-full-word-match","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        if index == len(word) - 1:\n            return True\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    found_word = False\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                found_word = True"}],"equivalentVariants":["Return true when index equals word length.","Return true when the current cell matches the final character."]}},{"id":"return-found","title":"Return the search verdict","description":"Return true when any DFS launch finds the word, and return false only after every start cell has been tried.","commonMistakes":["Returning true without checking the DFS result","Returning false before all start cells have been tried","Forgetting the final false return when no path exists"],"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"grid-recursive-search","fact":"returns_grid_search_verdict","scope":"return-found","readMode":"grid-recursive-search-value-query-v1"}]},"semanticSpec":{"intent":"Connect the DFS search result to the top-level boolean answer.","doneWhen":"The grid scan returns true from a successful recursive search and returns false after the scan finishes without a match.","shouldFailWhen":"The function omits either the successful early return or the final no-match false return.","roles":["grid scan","recursive helper","success return","failure return"],"mustProve":["A recursive search success returns true from the outer function.","The outer function returns false only after the grid launch scan has no successful path."],"mustNotAccept":["Only proving the helper's success base case.","Only returning true without a final false fallback."],"proofSnippets":[{"id":"py-word-search-return-found","language":"python","code":"def exist(board, word):\n    rows = len(board)\n    cols = len(board[0])\n    def dfs(r, c, index):\n        if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:\n            return False\n        if index == len(word) - 1:\n            return True\n        temp = board[r][c]\n        board[r][c] = '#'\n        found = (\n            dfs(r + 1, c, index + 1)\n            or dfs(r - 1, c, index + 1)\n            or dfs(r, c + 1, index + 1)\n            or dfs(r, c - 1, index + 1)\n        )\n        board[r][c] = temp\n        return found\n    for r in range(rows):\n        for c in range(cols):\n            if board[r][c] == word[0] and dfs(r, c, 0):\n                return True\n    return False"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Walk the grid from every matching start, marking each cell on the way in and restoring it on the way out so the board itself records the path.","workspacePanel":"code","body":["Marking a cell keeps a single walk from reusing it; restoring it on the way out is what lets a different path run through the same cell, which is exactly how a word that fails from one start can succeed from another.","Using the board as its own visited record means no extra space, and the four-neighbor recursion explores every route until one spells the word or all dead-end."],"takeaways":[{"title":"Mark in, restore out","body":"A cell is blocked only while its own walk runs; restoring it on return frees it for every other path."},{"title":"The board is the visited set","body":"Marking cells in place and undoing the mark avoids a separate visited structure entirely."},{"title":"O(m*n*4^L) time, O(L) space","body":"Each of the m*n cells can start a length-L walk that fans out four ways per step, and the only extra space is the recursion stack, L frames deep, since the marking is done in place."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
