Word Search

Check whether a word can be traced through touching cells of a letter grid, without using a cell twice.

Given a grid of letters board with m rows and n columns, and a string word, return true if the word can be traced in the grid. Each next letter of the word must sit in a cell that touches the previous one horizontally or vertically, and no cell may be used twice in the same word.

Example 1
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2
Input: same board, word = "SEE"
Output: true
Example 3
Input: same board, word = "ABCB"
Output: false
Explanation: after A, B and C, the last B would have to be the B that was already used.
Solution

The Idea

Picture a word-search puzzle in a newspaper, except that here the word may bend. You put a finger on the first letter and slide it to a touching cell for each next letter, never jumping and never landing on the same cell twice.

Write each cell as (row, column), counting from 0. In Example 1, ABCCED starts at A in (0, 0) and moves right to B at (0, 1) and C at (0, 2). It then goes down to C at (1, 2) and E at (2, 2), and left to D at (2, 1). That is six letters on six different cells, so the answer is true.

Example 3, ABCB, starts the same way: A, B and C along row 0. Then it needs a B next to the C at (0, 2). That C touches E on its right, another C below it, and the B at (0, 1), which the path has already used. Could a different path work? To answer false, every possible path has to be ruled out. Look at the picture below.

Left: the board with rows 0 to 2 and columns 0 to 3, and the path A, B, C along row 0. Right: the choices for ABCB from A at (0, 0). Each cell tries down, up, right and left. Wrong letters, cells off the grid and cells already on the path are cut short, and no branch reaches the last B.

On the left is the board, with its row and column numbers and the path so far: A, B, C. On the right, under "the choices for ABCB from A at (0, 0)", the search starts at A at (0, 0) and tries its neighbours in a fixed order: down, up, right, left. Down is S, the wrong letter, and up and left are off the grid, so those boxes are dashed: the search goes no further there. Right is B at (0, 1), which matches, and the same four tries start again from that B, in the row labelled "need C".

In the bottom row, the C at (0, 2) needs a B. Three boxes give a wrong letter or leave the grid, and the box "left: B" is marked "on the path". With all four directions failed, the search steps back to the B at (0, 1) and tries its last direction, left, which is the A already on the path.

So the search builds a path one choice at a time and, when a choice leads nowhere, takes that last cell off the path and tries the next direction from the cell before. Growing a path this way and undoing the last step when it fails is called backtracking. No branch from A at (0, 0) reaches the last B, and the other A, at (2, 0), has no B next to it, so ABCB gives false.

Solution Approach

Turning that idea into code means settling three things: where a path may start, how a path grows and when it stops, and how to keep a cell from being used twice. One optional check can also rule out some words before any search.

Where a path may start

Where does the word begin? In any cell that holds its first letter, and there is no way to tell in advance which one works. So the search tries every cell in turn, row by row, and stops at the first start that traces the whole word.

In Example 2, SEE, the first S at (1, 0) fails, because it touches A, A and F but no E. The second S, at (1, 3), works: down to E at (2, 3), then left to E at (2, 2).

Growing a path and stopping early

What does one step of the search do? It gets a cell and the position in the word that the cell should match, called index. If the cell is off the grid or holds a different letter, this branch fails at once. If it matches, the step tries the four neighbours with index + 1. When index reaches the end of the word, every letter has been matched.

A slower way would list every path of the word's length in the grid and compare each one with the word. Checking the letter at every step ends a path at its first wrong letter, like the dashed boxes in the picture, so most paths are never built at all.

Keeping a cell from being used twice

How does a step know that a cell is already on the path? While a cell is on the path, the search writes '#' into it. No letter of a word is '#', so the letter check fails there, just as for a wrong letter. When all four directions from the cell have been tried, its original letter goes back.

Why put the letter back? A later path may need that cell. Take the word CCB on the same board. The first C, at (0, 2), goes down to the C at (1, 2) and gets stuck, since that C touches no B. The search then starts from the second C, at (1, 2), and goes up to C at (0, 2) and left to B, so the answer is true. That path uses both C cells, which works only because the failed search from (0, 2) gave their letters back.

A separate grid of boolean flags for the cells on the path would work too. Marking the board itself saves that extra grid.

An optional check before searching

Can some words be rejected without searching at all? A word with more letters than the board has cells is too long for any path. Counting letters helps too: on the example board, which has one B, a word with two Bs cannot be traced, and ABCB from Example 3 is one. These checks never change the answer; they only save time on large boards.

Java Solution

The two methods exist and match work in these steps:

  1. First, exist goes over every cell with two loops, one for the row r and, inside it, one for the column c. For each cell it calls match(board, word, 0, r, c) to try that cell as the start of the word.
  2. match first checks whether index equals word.length(). If so, every letter has been matched, and it returns true.
  3. Next, it returns false if (r, c) is off the grid or board[r][c] is not word.charAt(index).
  4. Otherwise the cell matches. match keeps its letter in saved and writes '#' into the cell, so the path cannot come back to it.
  5. Then match calls itself for the four neighbours, down, up, right and left, each with index + 1, joined by ||. The || stops at the first direction that returns true, and the result goes into found.
  6. Finally, match writes saved back into the cell and returns found. exist returns true as soon as one start succeeds, and false once every cell has failed.

The main method searches the three example words, CCB and a 13-letter word on the example board, prints the board afterwards, and tries a board of a single cell.

Java
public class WordSearch {

    public static boolean exist(char[][] board, String word) {
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                if (match(board, word, 0, r, c)) {
                    return true;
                }
            }
        }
        return false;
    }

    // Can the letters of word from position index on be traced starting at cell (r, c)?
    private static boolean match(char[][] board, String word, int index, int r, int c) {
        if (index == word.length()) {
            return true;                                     // every letter matched
        }
        if (r < 0 || c < 0 || r >= board.length || c >= board[0].length
                || board[r][c] != word.charAt(index)) {
            return false;                                    // off the grid or wrong letter
        }
        char saved = board[r][c];
        board[r][c] = '#';                                   // mark the cell as on the path
        boolean found = match(board, word, index + 1, r + 1, c)    // down
                || match(board, word, index + 1, r - 1, c)         // up
                || match(board, word, index + 1, r, c + 1)         // right
                || match(board, word, index + 1, r, c - 1);        // left
        board[r][c] = saved;                                 // take the cell off the path
        return found;
    }

    public static void main(String[] args) {
        char[][] board = {
            {'A', 'B', 'C', 'E'},
            {'S', 'F', 'C', 'S'},
            {'A', 'D', 'E', 'E'}
        };
        for (String word : new String[] {"ABCCED", "SEE", "ABCB", "CCB", "ABCDEFGHIJKLM"}) {
            System.out.println(word + " -> " + exist(board, word));
        }
        for (char[] row : board) {
            System.out.println(new String(row));             // the board after all searches
        }
        char[][] single = {{'A'}};
        System.out.println("A on [A] -> " + exist(single, "A"));
        System.out.println("AA on [A] -> " + exist(single, "AA"));
    }
}

Running it prints:

Output
ABCCED -> true
SEE -> true
ABCB -> false
CCB -> true
ABCDEFGHIJKLM -> false
ABCE
SFCS
ADEE
A on [A] -> true
AA on [A] -> false

ABCCED and SEE give true and ABCB gives false, as in Examples 1 to 3. CCB -> true is the path from C at (1, 2) up to C at (0, 2) and left to B. ABCDEFGHIJKLM has 13 letters for 12 cells, so it prints false.

The rows ABCE, SFCS and ADEE show the board exactly as it started: every '#' was replaced by its letter again. In the last two lines, the one-cell board finds A, but AA would need that cell twice, so it prints false.

What if the line board[r][c] = saved; is left out? We ran the same program without it. ABCCED still prints true, but SEE and CCB print false, and the board rows come out as ####, #F## and ####. Every cell that a search matched kept its '#'. Even on a fresh board, CCB then gives false, because the first start leaves '#' in both C cells.

Complexity

The work is one search from each cell, and each search may branch at every letter of the word. Here L is the length of the word.

  • Time: O(m · n · 3L), because each of the m · n cells can start a search, and after the first letter each step has at most three new directions, as the cell it came from holds '#'.
  • Space: O(L), because the calls of match still open at any moment follow the current path, at most L + 1 deep, and the marks live in the board itself, so no extra grid is needed.

To look for many words in the same grid, store them in a trie, a tree of letters where words with the same beginning share a branch. One search then covers them all.