- 在大多数情况下,我们在能使用 BFS 时也可以使用 DFS。但是有一个重要的区别:
遍历顺序
- 与 BFS 不同,
更早访问的结点可能不是更靠近根结点的结点
。因此,你在 DFS 中找到的第一条路径可能不是最短路径
结点的处理顺序是
完全相反的顺序
,就像它们被添加
到栈中一样,它是后进先出(LIFO)。这就是我们在 DFS 中使用栈的原因
模板一 - 递归
当我们递归地实现 DFS 时,似乎不需要使用任何栈。但实际上,我们使用的是由系统提供的隐式栈,也称为调用栈
- 先访问根顶点
- 然后不断往下专,知道没有路可走
- 然后从栈顶一个一个的出栈
/*
* Return true if there is a path from cur to target.
*/
boolean DFS(Node cur, Node target, Set<Node> visited) {
return true if cur is target;
for (next : each neighbor of cur) {
if (next is not in visited) {
add next to visted;
return true if DFS(next, target, visited) == true;
}
}
return false;
}
模板二- 感觉是BFS
package com.company.myQueue; import java.util.*; public class Solution7 { /* * Return true if there is a path from cur to target. */ boolean DFS(Node root, int target) { Set<Node> visited = new HashSet<>(); Queue<Node> queue = new ArrayDeque<>(); //入栈类比函数入栈 queue.offer(root); //这的循环一次就是一次函数调用 while (!queue.isEmpty()) { Node cur = queue.peek(); if (cur.value == target) { return true; } for (Node next : cur.childrenNode) { if (!visited.contains(next)) { queue.offer(next); visited.add(next); } } queue.poll(); } return false; } }