深度优先搜索(用栈实现)

递归实现深度优先实际上就是栈

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']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值