Word Search
To solve this coding challenge, you need to implement a function that will check if a word exists within a given grid, where the word can be formed by sequentially adjacent cells. This involves a backtracking approach to explore every possible path by looking at each cell and its neighboring cells recursively.
Step-by-Step Explanation
- Initialization and Validation :
-
First, ensure the input grid (
board
word
- We will initialize a backtracking helper function to search for the word starting from any cell in the grid.
- Helper Function - Backtracking :
-
The backtracking function checks whether the word can be formed starting from a given cell
(i, j)
k
-
If
k
True
-
If the current position
(i, j)
False
- Marking and Exploring :
- Temporarily mark the current cell as visited by changing its value to avoid revisiting it during the search.
-
Explore the surrounding cells (up, down, left, right) by recursively calling the backtracking function with the next character position
k+1
- Restore the cell's original value after the exploration to backtrack correctly.
- Iterative Exploration :
-
Iterate over each cell of the grid, and for each cell, call the backtracking function starting with
k=0
-
If any of these calls return
True
True
- Result :
-
If no starting cell leads to the entire word being formed, return
False
Detailed Steps in Pseudocode
# Initialize the main function
function wordSearch(board, word):
# Define the backtracking function
function backtrack(row, col, index):
# If entire word is found
if index == length(word):
return True
# If out of grid bounds or current character does not match the word's character
if row < 0 OR row >= number of rows in board OR col < 0 OR col >= number of columns in board OR board[row][col] != word[index]:
return False
# Temporarily mark the cell as visited
temp = board[row][col]
board[row][col] = '/'
# Explore all four possible directions
found = backtrack(row + 1, col, index + 1) OR backtrack(row - 1, col, index + 1) OR backtrack(row, col + 1, index + 1) OR backtrack(row, col - 1, index + 1)
# Restore the cell's original value after exploring
board[row][col] = temp
return found
# Iterate over each cell in the grid
for each row in range(number of rows):
for each col in range(number of columns):
# Begin the backtrack search from each cell
if backtrack(row, col, 0):
return True
return False
Explanation
-
Function
wordSearch
-
Calls the
backtrack
-
If any call to
backtrack
True
True
-
If no such path is found, it returns
False
-
Function
backtrack
-
Checks if the whole word is matched by comparing if
index
-
Ensures that the current coordinates
(row, col)
-
Marks the cell as visited by temporarily setting its value to
'/'
- Recursively explores in four directions (downwards, upwards, rightwards, leftwards).
- After the exploration, it restores the original value of the cell to ensure the grid remains unaltered for other paths.
-
Returns
True