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.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(word == "") return true;
int m = board.size();
if(!m) return false;
int n = board[0].size();
if(!n) return false;
vector<vector<bool> > flag(m, vector<bool>(n, true));
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
{
if(board[i][j] == word[0])
{
flag[i][j] = false;
if(dfs(board, word, i, j, 1, flag)) return true;
flag[i][j] = true;
}
}
return false;
}
bool dfs(vector<vector<char> >& board, string word, int i, int j, int depth, vector<vector<bool> > flag)
{
if(depth == word.length()) return true;
int m = board.size();
int n = board[0].size();
for(int k = 0; k < 4; ++k)
{
int x = i + d[k][0];
int y = j + d[k][1];
if(x >= 0 && x < m && y >= 0 && y < n && flag[x][y] && board[x][y] == word[depth])
{
flag[x][y] = false;
if(dfs(board, word, x, y, depth + 1, flag)) return true;
flag[x][y] = true;
}
}
return false;
}
private:
int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
};