Backtracking & Exhaustive Search · 15 min · free lesson

Challenge: Grid Word Search

Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.

Core idea

A sibling path may legally reuse that cell. Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Walk matching neighbors while temporarily marking the current cell unavailable in this path.

O(rows*cols*4^L) worst · O(L) depth11 execution steps
main · before line 44Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputgrid=A word=B

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 44
fn word_exists(grid: &[Vec<u8>], word: &[u8]) -> bool {
    fn search(
        g: &[Vec<u8>],
        w: &[u8],
        r: usize,
        c: usize,
        i: usize,
        seen: &mut [Vec<bool>],
    ) -> bool {
        if seen[r][c] || g[r][c] != w[i] {
            return false;
        }
        if i + 1 == w.len() {
            return true;
        }
        seen[r][c] = true;
        let mut found = false;
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let (a, b) = (r as isize + dr, c as isize + dc);
            if a >= 0
                && b >= 0
                && a < g.len() as isize
                && b < g[0].len() as isize
                && search(g, w, a as usize, b as usize, i + 1, seen)
            {
                found = true;
                break;
            }
        }
        seen[r][c] = false;
        found
    }
    if word.is_empty() {
        return true;
    }
    if grid.is_empty() {
        return false;
    }
    let mut seen = vec![vec![false; grid[0].len()]; grid.len()];
    (0..grid.len()).any(|r| (0..grid[r].len()).any(|c| search(grid, word, r, c, 0, &mut seen)))
}
 
fn main() {
    let result = word_exists(&["A".as_bytes().to_vec()], "B".as_bytes()).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `grid=A word=B` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `grid=ABCE,SFCS,ADEE word=ABCCED`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Backtracking & Exhaustive Search infographic; panel 1 illustrates Word Grid Search.
Word Grid Search: follow panel 1 to see the operation, then trace this lesson's example.

Understand it

A sibling path may legally reuse that cell. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input grid=A word=B, the worked program returns false. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input grid=ABCE,SFCS,ADEE word=ABCCED; predict that result before opening the answer reveal. The precise contract is: Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path. On input grid=ABCE,SFCS,ADEE word=ABCCED, predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Walk matching neighbors while temporarily marking the current cell unavailable in this path. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. Most patterns here explore a decision tree; meet-in-the-middle instead enumerates two halves and combines them. Define the partial choice or subset summary that the pattern retains. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(rows*cols*4^L) worst · O(L) depth; explain which operation dominates it and how many times the input can trigger that operation. Test no solution, one solution, duplicate inputs, and the order in which candidates are tried if output order is observable. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Walk matching neighbors while temporarily marking the current cell unavailable in this path.

When to use it: path spelling and local grid constraints

Complexity: O(rows*cols*4^L) worst · O(L) depth

Input: grid=ABCE,SFCS,ADEE word=ABCCED

Read the code

fn word_exists(grid: &[Vec<u8>], word: &[u8]) -> bool {
    fn search(
        g: &[Vec<u8>],
        w: &[u8],
        r: usize,
        c: usize,
        i: usize,
        seen: &mut [Vec<bool>],
    ) -> bool {
        if seen[r][c] || g[r][c] != w[i] {
            return false;
        }
        if i + 1 == w.len() {
            return true;
        }
        seen[r][c] = true;
        let mut found = false;
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let (a, b) = (r as isize + dr, c as isize + dc);
            if a >= 0
                && b >= 0
                && a < g.len() as isize
                && b < g[0].len() as isize
                && search(g, w, a as usize, b as usize, i + 1, seen)
            {
                found = true;
                break;
            }
        }
        seen[r][c] = false;
        found
    }
    if word.is_empty() {
        return true;
    }
    if grid.is_empty() {
        return false;
    }
    let mut seen = vec![vec![false; grid[0].len()]; grid.len()];
    (0..grid.len()).any(|r| (0..grid[r].len()).any(|c| search(grid, word, r, c, 0, &mut seen)))
}

fn main() {
    let result = word_exists(&["A".as_bytes().to_vec()], "B".as_bytes()).to_string();
    println!("{result}");
}

Complete std-only word-grid-search program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement word-grid-search")
}

Try it

Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.

What success looks like: The private harness prints PASS word-grid-search. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for word-grid-search: with input grid=ABC word=CBA, what result should solve return?

Reveal the answer
  1. true
  2. false
  3. The valid input necessarily panics

For this input the result is true. A sibling path may legally reuse that cell. Compare this independent fixture with the worked trace: In the sample grid, ABCCED follows adjacent cells without reusing one. In grid AA with word AAA, there are only two cells, so the answer is false despite matching letters. Backtracking restores visited state after each attempted path.

Go deeper

Common misconception: “A cell may be reused twice within the same path”

A sibling path may legally reuse that cell. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: A sibling path may legally reuse that cell. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses grid=A word=B and computes false. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For grid=AA word=AAA, the independently calculated result is false. The complexity discussion uses O(rows*cols*4^L) worst · O(L) depth. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture grid=A word=B in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge grid=ABCE,SFCS,ADEE word=ABCCED.

Connections

  • Grid Word Search: When to Use It: path spelling and local grid constraints
  • Palindrome Partitioning: Mental Model: Choose each palindromic prefix as the next piece and recurse on the remaining suffix.
Reveal the Algorithm Atlas answer

true

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Grid Word Search (courseId "algorithms", lessonId "algorithm.word-grid-search.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.word-grid-search.challenge
Goal: A sibling path may legally reuse that cell. Parse a rectangular ASCII grid and word. Return whether four-neighbor moves spell the word without reusing a cell within one path.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.word-grid-search.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.