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.
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
Output: true
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
Output: false
From: LeetCode
Link: 79. Word Search
Main Idea:
The main concept here is to use Depth First Search (DFS) to explore the board. Starting from each cell, the algorithm tries to construct the word by moving either horizontally or vertically through adjacent cells. While doing so, the algorithm makes sure not to use the same cell more than once.
Details:
1. Starting Point:
2. DFS Function (dfs):
3. Avoiding Revisiting the Same Cell:
4. Result:
bool dfs(char** board, int i, int j, char* word, int index, int boardSize, int boardColSize) {
// Base case: if the current position is out of bounds or the current character does not match
if (i < 0 || i >= boardSize || j < 0 || j >= boardColSize || board[i][j] != word[index]) {
return false;
}
// If we've reached the end of the word, then we've found a match
if (index == strlen(word) - 1) {
return true;
}
char tmp = board[i][j];
board[i][j] = 0; // Mark the cell as visited
// Recursively search for the next character in all four directions (up, down, left, right)
bool found = dfs(board, i + 1, j, word, index + 1, boardSize, boardColSize)
|| dfs(board, i - 1, j, word, index + 1, boardSize, boardColSize)
|| dfs(board, i, j + 1, word, index + 1, boardSize, boardColSize)
|| dfs(board, i, j - 1, word, index + 1, boardSize, boardColSize);
board[i][j] = tmp; // Restore the cell value after the DFS
return found;
}
bool exist(char** board, int boardSize, int* boardColSize, char* word) {
for (int i = 0; i < boardSize; i++) {
for (int j = 0; j < boardColSize[0]; j++) {
// Start the DFS search from each cell in the board
if (dfs(board, i, j, word, 0, boardSize, boardColSize[0])) {
return true;
}
}
}
return false;
}