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.
Have you met this question in a real interview?
Yes
Example
Given board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
bug :
line 29
class Solution {
public:
/\*\*
\* @param board: A list of lists of character
\* @param word: A string
\* @return: A boolean
\*/
bool exist\(vector<vector<char> > &board, string word\) {
// write your code here
if \(word.empty\(\)\) {
return true;
}
if \(board.empty\(\) \|\| board\[0\].empty\(\)\) {
return false;
}
int n = board.size\(\);
int m = board\[0\].size\(\);
for \(int i = 0; i < n; ++i\) {
for \(int j = 0; j < m; ++j\) {
vector<vector<bool>> flag\(n, vector<bool>\(m, false\)\);
if \(dfs\(board, i, j, word, flag, 0\)\) {
return true;
}
}
}
return false;
}
bool dfs\(vector<vector<char> > &board, int i, int j, string& word, vector<vector<bool>>& flag, int pos\) {
if \(flag\[i\]\[j\] \|\| word\[pos\] != board\[i\]\[j\]\) {
return false;
}
if \(pos == word.length\(\) - 1\) {
return true;
}
flag\[i\]\[j\] = true;
vector<vector<int>> dirs = {{1,0}, {-1, 0}, {0, 1}, {0, -1}};
for \(auto& dir : dirs\) {
int ni = i + dir\[0\];
int nj = j + dir\[1\];
if \(ni >= 0 && ni < board.size\(\) && nj >= 0 && nj < board\[0\].size\(\)\) {
if \(dfs\(board, ni, nj, word, flag, pos + 1\)\) {
return true;
}
}
}
flag\[i\]\[j\] = false;
return false;
}
};