剑指offer12 矩阵中的路径
深度优先搜索(DFS)+剪枝
DFS解析:
- 递归参数:矩阵行列索引
i
和j
,目标字符在word
中 索引k
- 终止条件:
- 行列索引越界
- 当前矩阵字符与目标字符不符合(包含已访问的情况
- 成功条件:
- k = word.length - 1
- 递推工作:
- 标记当前矩阵元素,表示已访问
- 递归调用dfs,向上下左右四个方向搜索
- 向上返回结果,同时回复矩阵元素
ac代码:
var exist = function(board, word) {
const dfs = function(i, j, k){
if(i < 0 || i > board.length-1 || j < 0 || j > board[0].length-1 || word[k] !== board[i][j])
return false;
if(k === word.length-1) return true;
board[i][j] = " ";
let res = dfs(i-1, j, k+1) || dfs(i, j-1, k+1) || dfs(i+1, j, k+1) || dfs(i, j+1, k+1);
board[i][j] = word[k];
return res;
}
if(board.length === 0 || board[0].length === 0) return false;
for(let i = 0; i < board.length; i++){
for(let j = 0; j < board[0].length; j++){
let r = dfs(i, j, 0);
if(r) return true;
}
}
return false;
};