递归实现深度优先实际上就是栈
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
#栈的思想实现深度优先
def dfs(graph,start):
stack=[[start,0]]
searched=set()
searched.add(start)
res=[start]
while stack:
#stack[-1]表示从栈的最后一个表示的节点开始
(node,next_child_id)=stack[-1]
#print node ,next_child_id
#当到达树的最后一层时next_child_id = len(graph[node])=0
if(node not in graph)or (next_child_id>=len(graph[node])):
stack.pop()
continue
next_child=graph[node][next_child_id]
#栈的最后一个表示的节点的next_child_id+1
stack[-1][1]=stack[-1][1]+1
if next_child in searched:
continue
res.append(next_child)
searched.add(next_child)
#将当前节点的孩子压入栈
stack.append([next_child,0])
print res
dfs(graph,'you')
输出为
['you', 'alice', 'peggy', 'bob', 'anuj', 'claire', 'thom', 'jonny']