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.
Solution
C++
class Solution {
public:
int m,n;
bool exist(vector<vector<char>>& board, string word) {
m = board.size();
n = board[0].size();
if(m == 0 || n == 0) return false;
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(dfs(board, i, j, word, 0)) return true;
}
}
return false;
}
bool dfs(vector<vector<char> >& board, int i, int j, string word, int index) {
if(index == word.length()) return true;
if(i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[index]) return false;
char tmp = board[i][j];
board[i][j] = '#';
bool res = dfs(board, i+1, j, word, index+1) ||
dfs(board, i-1, j, word, index+1) ||
dfs(board, i, j+1, word, index+1) ||
dfs(board, i, j-1, word, index+1);
board[i][j] = tmp;
return res;
}
};
Explanation