深度优先搜索:从根节点A开始,每次从其中的一个邻居节点开始遍历,然后从邻居节点的邻居乡下遍历,直到找到目标,或者,当前节点不是目标,并且他没有邻居节点,那就出栈。然后从栈顶元素再找一个元素出栈,判断是不是目标,不是目标,判断一下时候有邻居,有邻居吧,入栈,并且其中一个邻居入栈,然后并且标记这个结点已经访问过了。
深度优先遍历:递归调用的形式:
/*
* 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;
}
/*
* Return true if there is a path from cur to target.
*/
boolean DFS(int root, int target) {
Set<Node> visited; //已被访问过
Stack<Node> s; // 栈
add root to s; // 根节点入栈
while (s is not empty) { // 栈非空
Node cur = the top element in s; // 栈顶元素出栈
return true if cur is target;
for (Node next : the neighbors of cur) { // 当前元素的邻居节点入栈
if (next is not in visited) { // 入栈代表访问过
add next to s;
add next to visited;
}
}
remove cur from s;
}
return false;
}