图的DFS遍历(python版本)

import networkx as nx
import matplotlib.pyplot as plt
def dfs(graph,node_start,max_step=10):
	assert max_step>=0 and node_start in graph.nodes()
	res_graph=nx.DiGraph()
	cur_step=0
	stack_list=[]
	visited={}
	print node_start
	visited[node_start]='1'
	stack_list.append(node_start)
	while len(stack_list)>0:
		cur_node=stack_list[-1]
		next_nodes=graph[cur_node].keys()
		if len(next_nodes)==0:#叶子节点要回退
			stack_list.pop()
			cur_step=cur_step-1
		else:
			if (len(set(next_nodes)-set(visited.keys()))==0 or cur_step>=max_step):
			#如果都被访问过 要回退
				stack_list.pop()
				cur_step=cur_step-1
			else:
				for i in next_nodes:
					res_graph.add_edge(cur_node,i)
					if i not in visited:
						print i
						visited[i]='1'
						stack_list.append(i)
						cur_step=cur_step+1
						break
	return res_graph

很久不写c++了,写了很久的sql,明显感觉代码能力退化了,利用python写了个DFS,思路很简单了,这里只是做个简单的记录,主要是区别在于,限制了一个step,当一个很大的图,全局遍历会很大,所以限制一个step,即由出发节点出发多少步就不往前探测了。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值