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 (board.size() == 0)
return false;
if (word.length() == 0)
return true;
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (board[i][j] == word[0]) {
vector<vector<char> > iarray(board);
bool ret = judge(iarray, i, j, word, 0);
if (ret == true)
return true;
}
}
}
return false;
}
bool judge(vector<vector<char> > &iarray, int i, int j, string &word, int k) {
if (k == word.length())
return true;
if (i >= 0 && j >= 0 && i < iarray.size() && j < iarray[i].size()
&& iarray[i][j] == word[k])
{
++k;
char temp = iarray[i][j];
iarray[i][j] = '#';
bool a = judge(iarray, i + 1, j, word, k);
bool b = judge(iarray, i - 1, j, word, k);
bool c = judge(iarray, i, j + 1, word, k);
bool d = judge(iarray, i, j - 1, word, k);
if (a || b || c || d)
return true;
else
{
iarray[i][j] = temp; //注意如果四个方向都找不到,记得回退
return false;
}
}
return false;
}
};