递归实现深度优先搜索
def DFS(cur, target, visited):return True if cur is targetfor (next : each neighbor of cur):if next is not in visited:add next to visited;return true if DFS(next, target, visited) == Truereturn False
不需要显示地使用栈,因为函数递归本身就是调用栈。
递归解决方案的优点是它更容易实现。 但是,存在一个很大的缺点:如果递归的深度太高,你将遭受堆栈溢出。 在这种情况下,您可能会希望使用 BFS,或使用显式栈实现 DFS。
def DFS(root, target):visitedstackadd root to stackwhile stack is not empty:cur = the top element of stackreturn true if cur is targetfor (next : the neighbors of cur):if next is not in visited:add next to stack;add next to visited;remove cur from stackreturn False
该逻辑与递归解决方案完全相同。 但我们使用 while 循环和栈来模拟递归期间的系统调用栈。
