Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
Starting Point: Find cells matching the first character
DFS Exploration: From each starting point, explore four directions
Marking Visited: Temporarily mark cells with '*' to avoid revisiting
Backtracking: Restore original characters after exploring each path
Visual Example
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.
