给出一个二维的字母板和一个单词,寻找字母板网格中是否存在这个单词。
单词可以由按顺序的相邻单元的字母组成,其中相邻单元指的是水平或者垂直方向相邻。每个单元中的字母最多只能使用一次。
样例
.
给出board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED", ->返回 true,
word = "SEE",-> 返回 true,
word = "ABCB", -> 返回 false
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
int m = board.size();
int n = board[0].size();
vector<vector<bool> > flag;
for (int i = 0; i < m; i++)
{
vector<bool> temp;
for (int j = 0; j < n; j++)
{
temp.push_back(false);
}
flag.push_back(temp);
}
bool found = false;
int k = word.length();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
visit(board, m, n, i, j, word, k, 0, flag, found);
if (found)
{
return true;
}
}
}
return false;
}
private:
void visit(vector<vector<char> > &board, int m, int n,
int row, int column, string &word, int k, int pos,
vector<vector<bool> > &flag, bool &found)
{
if (found)
{
return;
}
if (row < 0 || row >= m || column < 0 || column >= n)
{
return;
}
if (flag[row][column])
{
return;
}
int nextPos = pos;
if (board[row][column] == word[pos])
{
if (pos == k-1)
{
found = true;
return;
}
flag[row][column] = true;
nextPos = pos+1;
}
else
{
return;
}
visit(board, m, n, row-1, column, word, k, nextPos, flag, found);
visit(board, m, n, row+1, column, word, k, nextPos, flag, found);
visit(board, m, n, row, column-1, word, k, nextPos, flag, found);
visit(board, m, n, row, column+1, word, k, nextPos, flag, found);
flag[row][column] = false;
}
};
.