您的位置:首页 > 编程语言 > Python开发

图的DFS遍历(python版本)

2016-05-17 20:02 691 查看
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,即由出发节点出发多少步就不往前探测了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: