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
.
1:注意特殊情況;2:設置二維數組保存當前字符是不是已經使用過了。3:遍歷數組,數組中的每個字符與單詞的首字符相比較,如果相等的話,進行遞歸;4:注意遞歸結束情況,以及返回情況
bool exist(vector<vector<char> > &board, string word)
{
if(word.size() == 0 || board.size() == 0 || board[0].size() == 0)
{
return false;
}
int rows = (int)board.size();
int columns = (int)board[0].size();
int length = (int)word.size();
if(length > rows * columns)
{
return false;
}
vector<vector<bool> > flag(rows, vector<bool>(columns, false));
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
if(board[i][j] == word[0])
{
if(existCore(board, i, j, word, 1, flag))
{
return true;
}
}
}
}
return false;
}
bool existCore(vector<vector<char> > &board, int curX, int curY, string &word, int index, vector<vector<bool> > &flag)
{
if(word[index] == '\0')
{
return true;
}
flag[curX][curY] = true;
bool result = false;
if(curX - 1 >= 0 && flag[curX-1][curY] == false && board[curX-1][curY] == word[index])
{
result = existCore(board, curX-1, curY, word, index + 1, flag);
}
if(!result && curX + 1 < (int)board.size() && flag[curX+1][curY] == false && board[curX + 1][curY] == word[index])
{
result = existCore(board, curX + 1, curY, word, index + 1 , flag);
}
if(!result && curY - 1 >= 0 && flag[curX][curY-1] == false && board[curX][curY - 1] == word[index])
{
result = existCore(board, curX, curY - 1, word, index + 1, flag);
}
if(!result && curY + 1 < (int)board[curX].size() && flag[curX][curY + 1] == false && board[curX][curY + 1] == word[index])
{
result = existCore(board, curX, curY + 1, word, index + 1, flag);
}
flag[curX][curY] = false;
return result;
}