回溯法:
思想
https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
其中的ppt很清楚
复杂度
递归的空间复杂度是递归的深度*每次压栈所需的空间个数
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.empty() || board[0].empty())
return false;
//每个点调用dfs,有一个成功返回true
for(int i = 0; i < board.size(); i++)
for(int j = 0;j < board[0].size(); j++)
if(dfs(board, word, i, j, 0))
return true;
return false;
}
bool dfs(vector<vector<char>>& board, string word, int i, int j, int index){
if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[index])
return false;
if(index == word.size() - 1)
return true;
//执行到这里说明board[i][j]与word[index]相等
//将访问过的字母标记为.,这样判断board[i][j] != word[index]会直接返回false
char tmp = board[i][j];
board[i][j] = '.';
//递归
bool res = dfs(board, word, i + 1, j, index + 1) || dfs(board, word, i - 1, j, index + 1) ||
dfs(board, word, i, j + 1, index + 1) || dfs(board, word, i, j - 1, index + 1);
//还原
board[i][j] = tmp;
return res;
}
};