Word Search in Python

In Python, word search refers to finding if a given word exists in a 2D grid. The word can be formed by sequentially connecting adjacent cells horizontally or vertically. This problem is commonly solved using backtracking and Depth-First Search (DFS) algorithms.

Algorithm Overview

The word search algorithm follows these key steps:

  • Iterate through each cell in the 2D grid

  • For each cell matching the first character, start a DFS search

  • Use backtracking to explore all four directions (up, down, left, right)

  • Mark visited cells temporarily and restore them after exploration

Example Grid

Let's consider a 2D board where we want to find the word "SEE":

A B C E
S F C S
A D E E

Implementation

Complete Word Search Solution

class WordSearch:
    def exist(self, board, word):
        """
        Check if word exists in the board
        """
        rows = len(board)
        cols = len(board[0])
        
        # Try starting from each cell
        for i in range(rows):
            for j in range(cols):
                if board[i][j] == word[0]:
                    if self.dfs(board, word, i, j, 0):
                        return True
        return False
    
    def dfs(self, board, word, row, col, index):
        """
        Depth-first search with backtracking
        """
        # Base case: found complete word
        if index == len(word):
            return True
        
        # Check boundaries and character match
        if (row < 0 or row >= len(board) or 
            col < 0 or col >= len(board[0]) or 
            board[row][col] != word[index]):
            return False
        
        # Mark current cell as visited
        temp = board[row][col]
        board[row][col] = '*'
        
        # Explore all four directions
        found = (self.dfs(board, word, row + 1, col, index + 1) or  # down
                 self.dfs(board, word, row - 1, col, index + 1) or  # up
                 self.dfs(board, word, row, col + 1, index + 1) or  # right
                 self.dfs(board, word, row, col - 1, index + 1))    # left
        
        # Restore original character (backtrack)
        board[row][col] = temp
        
        return found

# Test the implementation
board = [["A","B","C","E"],
         ["S","F","C","S"],
         ["A","D","E","E"]]

word_search = WordSearch()
result = word_search.exist(board, "SEE")
print(f"Word 'SEE' exists: {result}")

# Test with another word
result2 = word_search.exist(board, "ABCCED")
print(f"Word 'ABCCED' exists: {result2}")
Word 'SEE' exists: True
Word 'ABCCED' exists: True

How the Algorithm Works

The algorithm uses backtracking to explore all possible paths:

  1. Starting Point: Find cells matching the first character

  2. DFS Exploration: From each starting point, explore four directions

  3. Marking Visited: Temporarily mark cells with '*' to avoid revisiting

  4. Backtracking: Restore original characters after exploring each path

Visual Example

A B C E S F C S A D E E Path for "SEE": S - Start E - Path Direction

Time and Space Complexity

  • Time Complexity: O(M × N × 4^L) where M×N is grid size and L is word length

  • Space Complexity: O(L) for recursion stack depth

Conclusion

Word search in Python uses backtracking and DFS to explore all possible paths in a 2D grid. The algorithm efficiently finds words by marking visited cells and restoring them after exploration, ensuring no cell is used twice in a single path.

Updated on: 2026-03-25T07:57:45+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements