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.
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(0 == word.size())
return true;
else
{
char firstChar = word.at(0);
int m = board.size();
int n = board[0].size();
vector<vector<char> > used(m);
for(int i = 0; i < m; ++i)
{
used[i].resize(n);
for(int j = 0; j < n; ++j)
used[i][j] = 0;
}
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if(firstChar == board[i][j]
&& canFound(board, i, j, 0, word, used))
return true;
}
}
return false;
}
}
bool canFound(vector<vector<char> >& board, int i, int j, int cur, string word, vector<vector<char> > used)
{
if(cur >= word.size()) return true;
if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size())
return false;
if(!used[i][j] && board[i][j] == word[cur])
{
used[i][j] = 1;
if(cur + 1 == word.size()) return true;
if(i + 1 < board.size() && !used[i+1][j] && canFound(board, i + 1, j, cur + 1, word, used))
return true;
if(i - 1 >= 0 && !used[i-1][j] && canFound(board, i - 1, j, cur + 1, word, used))
return true;
if(j + 1 < board[0].size() && !used[i][j+1] && canFound(board, i, j + 1, cur + 1, word, used))
return true;
if(j - 1 >= 0 && !used[i][j-1] && canFound(board, i, j - 1, cur + 1, word, used))
return true;
}
else
{
used[i][j] = 0;
return false;
}
}
};