解题思路
回溯法可以看成蛮力法的升级版,它从解决问题每一步的所有可能选项里系统地选择出一个可行的解决方案。回溯法非常适合由多个步骤组成的问题,并且每个步骤都有多个选项。当我们在某一步选择了其中一个选项时,就进入下一步,然后又面临新的选项。我们就这样重复选择,直至到达最终的状态。
举例如下
代码
class Solution {
public:
/*
x[4]、y[4]和dfs中for循环,共同构成遍历字符board的“左右上下”四个字符这一功能
*/
array<int,4> x = { 0,0,-1,1 };
array<int,4> y = { -1,1,0,0 };
bool exist(vector<vector<char>>& board, string word) {
//特判
if (board.empty() || word.empty()) return false;
int pathLength = 0;
for (int row = 0; row < board.size(); row++)
{
for (int col = 0; col < board[0].size(); col++)
{
//对每个点依次判断是否存在一条路径
if (hasPathCore(board, row, col, pathLength, word))
{
return true;
}
}
}
return false;
}
bool hasPathCore(vector<vector<char>>& board, int row, int col, int& pathLength, string word)
{
//递归边界
if (pathLength == word.size()) return true;
bool hasPath = false;
bool noOverIndex = (row >= 0 && row < board.size() && col >= 0 && col < board[0].size());//坐标是否越界
if (noOverIndex && board[row][col] == word[pathLength])//未越界,且该点字符和word字符相等(此处隐含了已被标记)
{
char temp = board[row][col];
++pathLength;//找一下个
board[row][col] = '*';//标记已看过
for (int i=0;i<4;i++)
{
//如果路径还不存在,依次遍历上下左右四个方向未被遍历的方向——剪枝作用
if(!hasPath) hasPath = hasPathCore(board, row + x[i], col + y[i], pathLength, word);
else break;
}
//回溯
if (!hasPath) {
--pathLength;
board[row][col] = temp;//还原
}
}
return hasPath;
}
};