Word Search

Word Search

Matrix
Backtracking

Problem Statement:

Given an m x n grid of characters board and a string word, return true if 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 letter cell may not be used more than once.

Example:

Input:

board = [["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]]
word = "ABCCED"

Output:

true

Algorithm:

  1. Try DFS from each cell in board
  2. Use backtracking with cell marking
  3. Check all four directions
  4. Compare characters sequentially

Complexity:

Time: O(N * M * 4^L) | Space: O(L) where L is word length

Java Solution:

public boolean exist(char[][] board, String word) {
    // Try starting from each cell
    for (int i = 0; i < board.length; i++) 
        for (int j = 0; j < board[0].length; j++) 
            if (existsDfs(board, word, 0, i, j)) 
                return true;
             
    return false;       
}

private boolean existsDfs(char[][] board, String word, 
                                     int index, int x, int y) {
    // Found the word
    if (index == word.length()) 
        return true;
    
    // Check boundaries and visited cells
    if (x < 0 || y < 0 || x >= board.length || 
        y >= board[0].length || board[x][y] == '.')
        return false;

    // Character doesn't match
    if (board[x][y] != word.charAt(index)) 
        return false;
    
    // Mark as visited
    board[x][y] = '.';
        
    // Try all four directions
    if (existsDfs(board, word, index + 1, x + 1, y) || 
        existsDfs(board, word, index + 1, x - 1, y) || 
        existsDfs(board, word, index + 1, x, y + 1) ||
        existsDfs(board, word, index + 1, x, y - 1)) {
        return true;
    } 
        
    // Restore the cell
    board[x][y] = word.charAt(index);
    return false;
}

Python Solution:

def exist(self, board: List[List[str]], word: str) -> bool:
    rows, cols = len(board), len(board[0])
    
    def dfs(x: int, y: int, i: int) -> bool:
        # Found the word
        if i == len(word):
            return True
            
        # Check boundaries and matches
        if (x < 0 or y < 0 or 
            x >= rows or y >= cols or
            board[x][y] == '.' or
            board[x][y] != word[i]):
            return False
            
        # Mark as visited
        temp = board[x][y]
        board[x][y] = '.'
        
        # Try all directions
        for dx, dy in [(0,1), (1,0), (0,-1), (-1,0)]:
            if dfs(x + dx, y + dy, i + 1):
                return True
                
        # Restore cell
        board[x][y] = temp
        return False
        
    # Try each cell as starting point
    for i in range(rows):
        for j in range(cols):
            if dfs(i, j, 0):
                return True
                
    return False

C++ Solution:

class Solution {
public:
    bool exist(vectorchar>>& board, string word) {
        for(int i = 0; i < board.size(); i++)
            for(int j = 0; j < board[0].size(); j++)
                if(dfs(board, word, i, j, 0))
                    return true;
        return false;
    }
    
private:
    bool dfs(vectorchar>>& board, string& word, 
             int x, int y, int i) {
        if(i == word.length())
            return true;
            
        if(x < 0 || x >= board.size() || 
           y < 0 || y >= board[0].size() || 
           board[x][y] == '.' || 
           board[x][y] != word[i])
            return false;
            
        char temp = board[x][y];
        board[x][y] = '.';
        
        bool found = dfs(board, word, x+1, y, i+1) ||
                       dfs(board, word, x-1, y, i+1) ||
                       dfs(board, word, x, y+1, i+1) ||
                       dfs(board, word, x, y-1, i+1);
                       
        board[x][y] = temp;
        return found;
    }
};
Previous
Previous

Letter Combinations of a Phone Number

Next
Next

Word search II