79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
We can use a 2D boolean array to mark whether the grid (i, j) is already visited or not so that we can avoid duplicate visiting grids.
bool helper(vector<vector<char> >& board, string& word, int idx, int i, int j, vector<vector<bool> >& visited) {
if (idx == word.length()) return true;
int m = board.size(), n = board[0].size();
if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] != word[idx]) return false;
visited[i][j] = true;
bool res = helper(board, word, idx + 1, i - 1, j, visited) ||
helper(board, word, idx + 1, i + 1, j, visited) ||
helper(board, word, idx + 1, i, j - 1, visited) ||
helper(board, word, idx + 1, i, j + 1, visited);
visited[i][j] = false;
return res;
}
bool exist(vector<vector<char>>& board, string word) { // time: O(m^2 * n^2); space: O(m * n)
if (board.empty() || board[0].empty()) return false;
int m = board.size(), n = board[0].size();
vector<vector<bool> > visited(m, vector<bool>(n, false));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (helper(board, word, 0, i, j, visited)) return true;
}
}
return false;
}
If the input 2D grids are allowed to modify, the additional boolean 2D array is not necessary by marking the original grid to some character such as '#' during searching.
bool helper(vector<vector<char> >& board, string& word, int idx, int i, int j) {
if (idx == word.length()) return true;
int m = board.size(), n = board[0].size();
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#' || board[i][j] != word[idx]) return false;
char ch = board[i][j];
board[i][j] = '#';
bool res = helper(board, word, idx + 1, i - 1, j) ||
helper(board, word, idx + 1, i + 1, j) ||
helper(board, word, idx + 1, i, j - 1) ||
helper(board, word, idx + 1, i, j + 1);
board[i][j] = ch;
return res;
}
bool exist(vector<vector<char>>& board, string word) { // time: O(m^2 * n^2); space: O(m * n)
if (board.empty() || board[0].empty()) return false;
int m = board.size(), n = board[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (helper(board, word, 0, i, j)) return true;
}
}
return false;
}
Last updated
Was this helpful?