Implementing Grid-Based Word Search Using Depth-First Search

The task requires determining if a target sequence of characters exists within a two-dimensional matrix. The characters must be formed by traversing adjacent cells horizontally or vertically, ensuring no cell is reused during the path construction for a single attempt.

Problem Constraints:

  • Input: A 2D character array board and a string word.
  • Output: Boolean value (true if found, false otherwise).
  • Movement: Directions are limited to Up, Down, Left, and Right.
  • Restriction: Once a cell is used in the current recursion stack, it cannot be part of that specific path again.

Algorithmic Approach

This problem is best solved using Recursive Backtracking combined with Pruning. The core idea is to treat every cell in the grid as a potential starting point. If the cell matches the first character of the word, a Depth First Search (DFS) explores the surrounding neighbors.

Key Steps:

  1. Iteration: Traverse the entire matrix. For each cell matching the first letter of the target, invoke the recursive search function.
  2. Recursive DFS: The helper function checks if the current grid position matches the required character at the current index of the target string.
  3. State Modification: To track visited cells without extra space complexity, temporari alter the grid cell's value (e.g., mark it with a placeholder like '#'). This ensures the same cell isn't revisited in the current path branch.
  4. Pruning: Immediately return false if boundaries are crossed or the current character does not match the target.
  5. Backtracking: After exploring all four directions from a cell, restore its original character to allow other paths to traverse it.

Implementation

The follwoing C++ solution utilizes a direction vector approach to simplify the four-neighbor exploration logic. Member variables for grid dimensions are passed as arguments to maintain stateless recursion where possible.

#include <vector>
#include <string>

class Solution {
public:
    bool exist(std::vector<std::vector<char>>& board, std::string word) {
        int rows = board.size();
        if (rows == 0) return false;
        int cols = board[0].size();
        
        // Iterate through every cell as a potential start point
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (dfs(board, word, 0, i, j, rows, cols)) {
                    return true;
                }
            }
        }
        return false;
    }

private:
    bool dfs(const std::vector<std::vector<char>>& board, const std::string& word, int k, int r, int c, int rows, int cols) {
        // Base Case: Successfully matched the last character of the word
        if (k == word.length() - 1) {
            return board[r][c] == word[k];
        }

        // Invalid Conditions: Out of bounds or Character Mismatch
        if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[k]) {
            return false;
        }

        // Mark current cell as visited
        char temp = board[r][c];
        board[r][c] = '#';

        // Explore 4 directions: Right, Left, Down, Up
        bool result = dfs(board, word, k + 1, r, c + 1, rows, cols) ||
                      dfs(board, word, k + 1, r, c - 1, rows, cols) ||
                      dfs(board, word, k + 1, r + 1, c, rows, cols) ||
                      dfs(board, word, k + 1, r - 1, c, rows, cols);

        // Restore the original character for backtracking
        board[r][c] = temp;

        return result;
    }
};

Complexity Analysis

  • Time Complexity: $O(N \times M \times 4^L)$, where $N$ is the number of rows, $M$ is the number of columns, and $L$ is the length of the word. In the worst case, we visit every cell ($N \times M$), and for each start node, we explore up to 3 new directions at each depth step ($4^L$ is an upper bound approximation, strictly $3^{L}$ after the first move).
  • Space Complexity: $O(L)$. The auxiliary space is dictated by the maximum depth of the recursion stack, which corresponds to the length of the word. No additional data structures like hash sets are used for visited status.

Tags: algorithms C++ depth-first-search backtracking Matrix Traversal

Posted on Sun, 24 May 2026 18:06:08 +0000 by TheSaint97