个人理解
DFS(深度优先搜索)和BFS类似,也是一种简便的图搜索算法,它的主要思想是:访问每一个分支到最深位置,直到不能继续为止。
图解
现在我们要找到从A节点到G节点的路径(不一定是最优的),DFS步骤如下:
1、从根节点A开始,选择节点B的路径,并回溯,直到到达节点E,无法再深入
2、接下来回溯到A,选择节点C的路径,选择E节点时,发现E已经被访问过了,回溯到C节点
3、选择节点F的路径,并且回溯,直到到达G节点
4、这样,A节点到G节点的路径为:A->C->F->G
伪代码:
boolean DFS(Node root, Node target) {
Set<Node> vistised;
Stack<Node> stack;
add root node to vistised;
add root node to stack;
while(stack is not empty) {
Node cur = top node of stack;
if (cur == target) return true;
for (Node next : child nodes of cur) {
if (next is not visisted) {
add next to vistised;
add next to stack;
}
}
remove cur from stack;
}
return false;
}
力扣对应例题
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
https://leetcode-cn.com/problems/decode-string/
https://leetcode-cn.com/problems/keys-and-rooms/