版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hit_shaoqi/article/details/82378139
def DFS_graph(graph,v0):
vnum = graph.vertex_num()
visited = [0]*vnum;
visited[v0]=1
DFS_seq = [v0]
st = SStack()
st.push((0,graph.out_edges(v0))
while not st.is_empty():
i,edges = st.pop()
if i<len(edges):
v,e = edges[i]
st.push((i+1,edges))
if not visited[v]:
DFS_seq.append(v) //如果是新的结点,则加载到seq序列中
visited[v]=1
st.push(0,graph.out_edges(v))
return DFS_seq
摘自裘宗燕的python数据结构
使用堆栈避免递归。注意:栈里记录了访问邻接矩阵行,以及其列坐标
while循环里:
1. 弹 pop
2.记录当前行以及i, 如果该行没有到尽头,压入该行下一个;
3.访问当前行的i,如果没有访问过则压栈
即 弹;压;如果新,压