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
Check if a word exists in a grid or not in Python
When working with grids or matrices of characters, we often need to search for words that can appear horizontally, vertically, or diagonally. This problem involves finding whether a given word exists in a 2D grid by checking all possible directions from each starting position.
Problem Understanding
Given a grid of characters and a target word, we need to check if the word exists in the grid. The word can be found in four directions ?
- Horizontally left to right
- Horizontally right to left
- Vertically top to bottom
- Vertically bottom to top
Here's the sample grid we'll work with ?
| p | g | h | s | f |
| y | k | d | g | h |
| t | k | g | h | i |
| h | n | s | j | s |
| o | j | f | g | h |
| n | r | t | y | u |
For the word "python", we should return True since it can be found vertically in the first column.
Algorithm Approach
We use a recursive backtracking approach ?
- Start from each cell in the grid
- If the current character matches the first character of our word, begin the search
- Recursively check all four directions (up, down, left, right)
- Mark visited cells temporarily to avoid revisiting
- Backtrack by restoring the original character
Implementation
def find_word_in_grid(grid, word):
def dfs(row, col, index):
# Base case: found the complete word
if index == len(word):
return True
# Boundary checks
if (row < 0 or row >= len(grid) or
col < 0 or col >= len(grid[0]) or
grid[row][col] != word[index]):
return False
# Mark current cell as visited
temp = grid[row][col]
grid[row][col] = '#'
# Check all four directions
found = (dfs(row - 1, col, index + 1) or # up
dfs(row + 1, col, index + 1) or # down
dfs(row, col - 1, index + 1) or # left
dfs(row, col + 1, index + 1)) # right
# Backtrack: restore original character
grid[row][col] = temp
return found
# Early exit for impossible cases
if len(word) > len(grid) * len(grid[0]):
return False
# Try starting from each cell
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == word[0]:
if dfs(row, col, 0):
return True
return False
# Test with the example grid
grid = [
['p', 'g', 'h', 's', 'f'],
['y', 'k', 'd', 'g', 'h'],
['t', 'k', 'g', 'h', 'i'],
['h', 'n', 's', 'j', 's'],
['o', 'j', 'f', 'g', 'h'],
['n', 'r', 't', 'y', 'u']
]
word = "python"
result = find_word_in_grid(grid, word)
print(f"Word '{word}' found: {result}")
Word 'python' found: True
How It Works
The algorithm works by ?
- Grid Traversal: We iterate through each cell in the grid
- Character Matching: When we find a cell matching the first character of our word, we start a depth-first search
- Recursive Search: From each matching cell, we explore all four directions recursively
- Backtracking: We temporarily mark visited cells with '#' to avoid cycles, then restore them
- Success Condition: If we match all characters of the word, we return True
Testing with Different Words
# Test with multiple words
grid = [
['p', 'g', 'h', 's', 'f'],
['y', 'k', 'd', 'g', 'h'],
['t', 'k', 'g', 'h', 'i'],
['h', 'n', 's', 'j', 's'],
['o', 'j', 'f', 'g', 'h'],
['n', 'r', 't', 'y', 'u']
]
test_words = ["python", "ghost", "xyz", "pg"]
for word in test_words:
result = find_word_in_grid([row[:] for row in grid], word) # Create copy
print(f"'{word}': {result}")
'python': True 'ghost': False 'xyz': False 'pg': True
Time and Space Complexity
- Time Complexity: O(N × M × 4^L) where N×M is grid size and L is word length
- Space Complexity: O(L) for recursion stack depth
Conclusion
This backtracking approach efficiently searches for words in a 2D grid by exploring all possible paths from each starting position. The key insight is using temporary marking to avoid revisiting cells during the current search path.
