BackendML

Word Search

Medium3 min read
The Word Search problem requires determining whether a given word exists in a 2D grid of characters by connecting adjacent cells.

Problem

Given an m × n grid of characters board and a string word, return true if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring.

The same cell may not be used more than once in the same word.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

board = [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
]

word = "ABCCED"

Output

true

Solution

This solution uses Backtracking to search for the word starting from every cell in the grid.

For each cell, the algorithm checks whether its character matches the current character of the word. If it matches, the cell is marked as visited and the search continues in the four possible directions: up, down, left, and right.

If the complete word is found, the recursion returns true. If a path does not lead to the word, the cell is unmarked so it can be used again in another search path.

The cell is marked and then restored after the recursive call. This is the backtracking step that prevents the same cell from being used twice in the current path while allowing it to be used by other paths.
public boolean exist(char[][] board, String word) {
    int rows = board.length;
    int cols = board[0].length;

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            if (backtrack(board, word, row, col, 0)) {
                return true;
            }
        }
    }
    return false;
}

private boolean backtrack(char[][] board, String word,
        int row, int col, int index) {

    // Complete word is found.
    if (index == word.length()) {
        return true;
    }

    // Check boundaries and character match.
    if (row < 0 || row >= board.length ||
        col < 0 || col >= board[0].length ||
        board[row][col] != word.charAt(index)) {
        return false;
    }

    // Mark the cell as visited.
    char original = board[row][col];
    board[row][col] = '#';

    // Explore all four directions.
    boolean found =
        backtrack(board, word, row - 1, col, index + 1) ||
        backtrack(board, word, row + 1, col, index + 1) ||
        backtrack(board, word, row, col - 1, index + 1) ||
        backtrack(board, word, row, col + 1, index + 1);

    // Undo the choice.
    board[row][col] = original;
    return found;
}

Complexity

Let m × n be the size of the grid and L be the length of the word. The algorithm starts a search from every cell and can explore up to four directions at each step. After the first cell, one direction is the cell from which we came, so at most three new directions are explored.

The worst-case time complexity is O(m × n × 3L).

The recursion depth is at most O(L), so the auxiliary space complexity is O(L), excluding the input grid.

Comments

No comments yet. Ask a question or share what helped.