AlgoTales · Roadmap

Word search

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Word search on a letter grid combines a trie with backtracking. The trie tells you instantly whether the letters collected so far could still grow into a real word, so you stop exploring hopeless paths early.

Practical use cases

  • Web app: Letter-grid game in the browser. A Wordscapes-like web game shows a 4 by 4 grid and highlights every dictionary word the player missed. Trying all paths through 16 tiles is huge, but the trie says "no word starts with QZ" and the solver drops that branch at once, so the answer shows in milliseconds. Players get the "words you missed" screen without any waiting spinner.
  • Web app: Keyword finder in a scanned form grid. A document-processing page receives text laid out in a grid and must find which listed keywords appear along rows, columns or turns. Checking the trie after each added letter prevents wandering through paths that cannot spell any keyword. This keeps the page responsive even when the grid is large and the keyword list has hundreds of entries.
  • System: Genome scans and game AI. Searching for any of many short motifs in a grid-like or sequence structure, or letting a game computer opponent choose words, uses the same prune-with-prefix idea to avoid exploring millions of useless paths. The sooner a dead end is recognised, the more of the search tree is never visited at all.

The story: The Mohalla Letter Grid

During Diwali, the kids of the mohalla drew a giant letter grid in chalk on the courtyard floor. The game: hop from letter to neighbouring letter (up, down, left, right, never the same tile twice) and spell words from a list. First team to find all the words wins a box of sweets.

Aarav tried the lazy way: take word 1, search the whole grid for it; then word 2, again the whole grid; then word 3... With a list of fifty words, his team was out of breath before they finished the first ten.

Mira whispered, "Flip it. Don't chase each word. Start from a tile and hop, and keep a finger on the lane board (trie) of the word list. The board tells you after every hop whether any word still starts with what you spelled. If it says no, stop that hop immediately and step back."

That is the famous Word Search (a Boggle solver): a depth-first search on the grid that walks the trie in lockstep, so one sweep finds every word and dead ends are cut after a single wrong letter. When a word is found, take it off the board so it is not counted twice, and un-mark the tile when you step back (backtracking).

How to spot this problem, and where you need it

You must find many words hidden in a grid by moving between neighbours, and trying every possible path is far too slow because the number of paths explodes.

Signs you need it

  • The input is a grid of letters and a list of words, and words are formed by moving to adjacent cells.
  • Searching each word separately across the grid repeats the same walking again and again.
  • Your solution times out because it keeps extending paths that obviously cannot be words.
  • The problem name is "Word Search II", "Boggle" or "find all words on the board".

Where to use it in a project

  • Browser word games and puzzle solver pages with letter boards.
  • Tools that look for any of many keywords inside grid-like data such as scanned tables.

The solution

Put all the target words into a trie. From each cell, walk the grid with backtracking while moving down the trie in step. If the trie has no child for the next letter, stop at once and step back. Whenever you arrive at a node marked as a word end, record that word. All words are searched in one sweep instead of one sweep per word.

Payoff: Before: one full grid search per word, 1,000 words means 1,000 sweeps. After: a single sweep that abandons dead ends immediately.

Explain it like I am 8

You hop between letter tiles to spell a word. A magic lane board whispers "keep going" or "stop, no word starts like that". When it whispers stop, you do not waste time on that path. You step back and try another tile.

How it works, step by step

  1. Put all dictionary words in a trie. Each end box remembers its word.
  2. For every grid cell, start a DFS from the trie's root.
  3. On a cell: if the trie has no child for its letter (or the cell is already used), stop this path.
  4. Otherwise step into that child; if it holds a word, record it and clear it so it is not found twice.
  5. Mark the cell used, try the 4 neighbours, then unmark it when coming back (backtracking).

The code in four languages

PHP

<?php
class TNode {
    public array $kids = [];
    public ?string $word = null;      // set at the end box of a word
}

function findWords(array $grid, array $words): array {
    $root = new TNode();
    foreach ($words as $w) {          // put all words in one trie
        $n = $root;
        foreach (str_split($w) as $ch) { $n->kids[$ch] ??= new TNode(); $n = $n->kids[$ch]; }
        $n->word = $w;
    }
    $found = [];
    for ($r = 0; $r < count($grid); $r++) {
        for ($c = 0; $c < count($grid[0]); $c++) {
            dfs($grid, $r, $c, $root, $found);
        }
    }
    sort($found);
    return $found;
}

function dfs(array &$g, int $r, int $c, TNode $parent, array &$found): void {
    $ch = $g[$r][$c];
    if ($ch === '#' || !isset($parent->kids[$ch])) { return; }   // used tile or no word goes this way
    $node = $parent->kids[$ch];
    if ($node->word !== null) {
        $found[] = $node->word;
        $node->word = null;                                       // do not report it twice
    }
    $g[$r][$c] = '#';                                             // mark tile used
    foreach ([[1, 0], [-1, 0], [0, 1], [0, -1]] as [$dr, $dc]) {
        $nr = $r + $dr;
        $nc = $c + $dc;
        if ($nr >= 0 && $nr < count($g) && $nc >= 0 && $nc < count($g[0])) {
            dfs($g, $nr, $nc, $node, $found);
        }
    }
    $g[$r][$c] = $ch;                                             // backtrack: free the tile
}

$grid = [['c', 'a', 't'], ['a', 'r', 's'], ['b', 'e', 'd']];
echo implode(', ', findWords($grid, ['cat', 'car', 'cab', 'cats', 'bed', 'dog'])) . PHP_EOL;

JavaScript

class TNode {
  constructor() {
    this.kids = {};
    this.word = null;        // set at the end box of a word
  }
}

function findWords(grid, words) {
  const root = new TNode();
  for (const w of words) {   // put all words in one trie
    let n = root;
    for (const ch of w) { if (!n.kids[ch]) n.kids[ch] = new TNode(); n = n.kids[ch]; }
    n.word = w;
  }
  const found = [];

  function dfs(r, c, parent) {
    const ch = grid[r][c];
    if (ch === '#' || !parent.kids[ch]) return;     // used tile or no word goes this way
    const node = parent.kids[ch];
    if (node.word !== null) {
      found.push(node.word);
      node.word = null;                             // do not report it twice
    }
    grid[r][c] = '#';                               // mark tile used
    for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
      const nr = r + dr, nc = c + dc;
      if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length) dfs(nr, nc, node);
    }
    grid[r][c] = ch;                                // backtrack: free the tile
  }

  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) dfs(r, c, root);
  }
  return found.sort();
}

const grid = [['c', 'a', 't'], ['a', 'r', 's'], ['b', 'e', 'd']];
console.log(findWords(grid, ['cat', 'car', 'cab', 'cats', 'bed', 'dog']).join(', '));

Java

import java.util.*;

public class Main {
    static class TNode {
        Map<Character, TNode> kids = new HashMap<>();
        String word = null;           // set at the end box of a word
    }

    static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    static List<String> findWords(char[][] grid, String[] words) {
        TNode root = new TNode();
        for (String w : words) {      // put all words in one trie
            TNode n = root;
            for (char ch : w.toCharArray()) {
                n.kids.putIfAbsent(ch, new TNode());
                n = n.kids.get(ch);
            }
            n.word = w;
        }
        List<String> found = new ArrayList<>();
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                dfs(grid, r, c, root, found);
            }
        }
        Collections.sort(found);
        return found;
    }

    static void dfs(char[][] g, int r, int c, TNode parent, List<String> found) {
        char ch = g[r][c];
        if (ch == '#' || !parent.kids.containsKey(ch)) return;   // used tile or no word goes this way
        TNode node = parent.kids.get(ch);
        if (node.word != null) {
            found.add(node.word);
            node.word = null;                                    // do not report it twice
        }
        g[r][c] = '#';                                           // mark tile used
        for (int[] d : DIRS) {
            int nr = r + d[0], nc = c + d[1];
            if (nr >= 0 && nr < g.length && nc >= 0 && nc < g[0].length) {
                dfs(g, nr, nc, node, found);
            }
        }
        g[r][c] = ch;                                            // backtrack: free the tile
    }

    public static void main(String[] args) {
        char[][] grid = {{'c', 'a', 't'}, {'a', 'r', 's'}, {'b', 'e', 'd'}};
        String[] words = {"cat", "car", "cab", "cats", "bed", "dog"};
        System.out.println(String.join(", ", findWords(grid, words)));
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

type TNode struct {
	kids map[byte]*TNode
	word string // set at the end box of a word ("" = none)
}

func newTNode() *TNode { return &TNode{kids: map[byte]*TNode{}} }

var dirs = [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}

func findWords(grid [][]byte, words []string) []string {
	root := newTNode()
	for _, w := range words { // put all words in one trie
		n := root
		for i := 0; i < len(w); i++ {
			if n.kids[w[i]] == nil {
				n.kids[w[i]] = newTNode()
			}
			n = n.kids[w[i]]
		}
		n.word = w
	}
	var found []string

	var dfs func(r, c int, parent *TNode)
	dfs = func(r, c int, parent *TNode) {
		ch := grid[r][c]
		node := parent.kids[ch]
		if ch == '#' || node == nil { // used tile or no word goes this way
			return
		}
		if node.word != "" {
			found = append(found, node.word)
			node.word = "" // do not report it twice
		}
		grid[r][c] = '#' // mark tile used
		for _, d := range dirs {
			nr, nc := r+d[0], c+d[1]
			if nr >= 0 && nr < len(grid) && nc >= 0 && nc < len(grid[0]) {
				dfs(nr, nc, node)
			}
		}
		grid[r][c] = ch // backtrack: free the tile
	}

	for r := range grid {
		for c := range grid[0] {
			dfs(r, c, root)
		}
	}
	sort.Strings(found)
	return found
}

func main() {
	grid := [][]byte{{'c', 'a', 't'}, {'a', 'r', 's'}, {'b', 'e', 'd'}}
	words := []string{"cat", "car", "cab", "cats", "bed", "dog"}
	fmt.Println(strings.Join(findWords(grid, words), ", "))
}

Time: O(cells x 3^L) · Extra space: O(total letters + L). In theory each start can branch into three new directions per letter (L = longest word), but the trie prunes dead paths so real runs are far faster.

Watch out for

  • Forgetting to un-mark the cell when backtracking, so later paths think the tile is used.
  • Reporting the same word twice (clear the stored word after finding it).
  • Searching word by word instead of using one trie, repeating the grid sweep for each word.

Quick check

  1. What does the trie do for us during the grid DFS?
    • Sorts the grid
    • Tells us instantly if any word still starts with the letters so far
    • Stores visited cells
  2. Why mark a cell as used and then restore it?
    • A tile may not be reused in the same word, but other paths can use it
    • To make the grid smaller
    • To count the cells
  3. Why set node.word to null after finding it?
    • To free memory only
    • So the same word is not reported again from another path
    • Because the trie needs it