题意:在一个char的二维数组里头找给出的一个字符串,找的方向只能上下左右。且每个char都最多只能用一次。
比较容易忽略的是每个char最多只能用一次,所以,需要一个visited数组,记录是否已经被访问了。关键点也在于visited的维护,如果当前路径不是合理路径,记得visited[i][j]得重新置为false.下面是我的代码。
bool findNext(vector<vector<char>> chVec,vector<vector<bool>>&visited,int i, int j, string word, int k, int d)
{
bool result = false;
if (k == word.size())
return true;
//往上
visited[i][j] = true;
if (i - 1 >= 0 && chVec[i - 1][j] == word[k] && !visited[i-1][j])
result = findNext(chVec,visited, i - 1, j, word, k + 1, 1);
if (!result)
//往下
if (i + 1<chVec.size() && chVec[i + 1][j] == word[k] && !visited[i+1][j])
result = findNext(chVec,visited, i + 1, j, word, k + 1, -1);
if (!result)
//往左
if (j - 1 >= 0 && chVec[i][j - 1] == word[k] &&!visited[i][j-1])
result = findNext(chVec,visited, i, j - 1, word, k + 1, -2);
if (!result)
//往右
if (j + 1<chVec[0].size() && chVec[i][j + 1] == word[k] && !visited[i][j+1])
result = findNext(chVec,visited, i, j + 1, word, k + 1, 2);
if (!result)
visited[i][j] = false;
return result;
}
bool exist(vector<vector<char>>& board, string word) {
//word=' '
int row = board.size();
int column = 0;
if (row != 0)
column = board[0].size();
if (word == " " || word == "" || row == 0 || word.size()>row*column)
return false;
for (int i = 0; i<row; i++)
for (int j = 0; j<column; j++)
{
if (board[i][j] == word[0])
{
vector<bool> temp(column, false);
vector<vector<bool>> visited(row, temp);
visited[i][j] = true;
if (findNext(board,visited ,i, j, word, 1, 0))
return true;
}
}
return false;
}