Algorithm
Complexity
Boggle Game
Optimization
Computer Science

On of solution to solve boggle

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A practical way to solve Boggle is to search the board with depth-first search while using a trie to prune impossible prefixes. This does not make the problem magically easy in the theoretical worst case, but it turns an otherwise explosive search into something efficient enough for real boards and dictionaries.

Why a Naive Solver Is Too Slow

In Boggle, you can start from any cell and move to any of its neighbors, including diagonals, without reusing a cell in the same word path. If you try every path blindly and only check whether the final string is in the dictionary, the search blows up quickly.

The key wasted work is obvious in hindsight:

  • many partial paths can never become dictionary words
  • a naive search keeps exploring them anyway

So the first real optimization is to stop searching as soon as the current letter path is not a prefix of any valid word.

Use a Trie for Prefix Pruning

A trie stores dictionary words character by character. It answers two useful questions for every prefix:

  • does this prefix exist in any dictionary word
  • does this prefix already complete a full word

That is exactly what a Boggle solver needs. During board traversal, if the current path is not present in the trie, the search can stop immediately.

Here is a small trie implementation in Python:

python
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_word = False
5
6
7def insert(root, word):
8    node = root
9    for ch in word:
10        node = node.children.setdefault(ch, TrieNode())
11    node.is_word = True
12
13
14def build_trie(words):
15    root = TrieNode()
16    for word in words:
17        insert(root, word)
18    return root

The trie does not solve the problem by itself, but it gives the board search a fast prefix filter.

Search the Board with DFS and Backtracking

The board traversal is a depth-first search with backtracking. From each cell:

  1. add the current letter to the path
  2. walk the trie to the child node for that letter
  3. if the path forms a word, record it
  4. recursively explore all valid neighbors
  5. backtrack by unmarking the cell

A complete solver looks like this:

python
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_word = False
5
6
7def insert(root, word):
8    node = root
9    for ch in word:
10        node = node.children.setdefault(ch, TrieNode())
11    node.is_word = True
12
13
14def build_trie(words):
15    root = TrieNode()
16    for word in words:
17        insert(root, word)
18    return root
19
20
21def solve_boggle(board, words):
22    rows, cols = len(board), len(board[0])
23    trie = build_trie(words)
24    found = set()
25
26    def dfs(r, c, node, path, visited):
27        ch = board[r][c]
28        if ch not in node.children:
29            return
30
31        next_node = node.children[ch]
32        path += ch
33
34        if next_node.is_word:
35            found.add(path)
36
37        visited.add((r, c))
38
39        for dr in (-1, 0, 1):
40            for dc in (-1, 0, 1):
41                if dr == 0 and dc == 0:
42                    continue
43                nr, nc = r + dr, c + dc
44                if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in visited:
45                    dfs(nr, nc, next_node, path, visited)
46
47        visited.remove((r, c))
48
49    for r in range(rows):
50        for c in range(cols):
51            dfs(r, c, trie, "", set())
52
53    return sorted(found)
54
55
56board = [
57    ["t", "e", "s", "t"],
58    ["a", "r", "e", "n"],
59    ["m", "o", "d", "l"],
60    ["p", "y", "t", "h"],
61]
62
63dictionary = ["test", "ten", "tree", "model", "python", "are"]
64print(solve_boggle(board, dictionary))

This solver is already good enough to demonstrate the classic approach clearly.

Why This Is Efficient in Practice

The trie makes the search practical because most random paths die quickly. Without prefix pruning, a search from each cell explores enormous numbers of paths that cannot possibly become words.

With a trie:

  • impossible prefixes stop immediately
  • successful paths continue only while they remain dictionary-consistent
  • repeated dictionary lookups become cheap prefix transitions

This is why trie-plus-DFS is the standard solution rather than plain DFS with repeated string lookups in a set.

Complexity Discussion

It is tempting to describe the solver as linear because trie lookup per character is cheap. That is misleading.

The running time still depends on:

  • board size
  • branching factor
  • maximum word length
  • how much prefix sharing exists in the dictionary

The better description is:

  • worst-case search remains combinatorial
  • trie pruning makes it efficient in practice on normal boards and dictionaries

That distinction matters if you care about algorithmic precision rather than just implementation advice.

Common Pitfalls

The most common mistake is using DFS without prefix pruning. That explores far too many impossible paths.

Another issue is forgetting that a cell cannot be reused within the same word path. If you do not track visited cells per recursive path, the solver produces invalid words.

People also often store results in a list and then remove duplicates later. A set is simpler and avoids repeated words naturally.

Finally, Boggle variants sometimes treat Qu as one cube. If your board uses that rule, the solver must model that tile explicitly rather than assuming one cell equals one character.

Summary

  • A practical Boggle solver combines DFS, backtracking, and a trie.
  • The trie provides prefix pruning, which removes huge amounts of wasted search.
  • DFS handles board traversal and visited-cell tracking.
  • The algorithm is efficient in practice, but not truly linear in the worst case.
  • Correct handling of visited cells and result deduplication is essential for a valid solver.

Course illustration
Course illustration

All Rights Reserved.