图深度优先搜索DFS
刚刚写了图的广度优先算法,现在完成深度优先算法DFS,color等的意义和上一篇一致,但f用于记录完成时间。
DFS
color = {}
pai = {}
d = {}
time = 0
f = {} # 记录完成时间
def DFS(G):
for u in G.keys():
color[u] = 'WHITE'
pai[u] = 'NIL'
time = 0
for u in G.keys():
if color[u] == 'WHITE':
DFS_VISIT(u)
def DFS_VISIT(u):
print u
color[u] = 'GRAY' # White vertex u has just been discovered.
global time
time += 1
d[u] = time
for v in G[u]: # Explore edge(u, v).
if color[v] == 'WHITE':
pai[v] = u
DFS_VISIT(v)
color[u] = 'BLACK' # Blacken u; it is finished.
time += 1
f[u] = time
G = {'A':['B','C'],'B':['D'],'C':['E'],'D':['C','E'],'E':[]}
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。