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

topological sort python recursive and iterative

2015-03-20 03:34 465 查看
Define a DAG we need to find a path so that we can follow the path and get the result.

graph={'A':['B','C'],'B':['D','E'],'C':['B','F'],'D':[],'E':[],'F':[]}

def dfs(graph):
stack=[graph.keys()[0]]
visit=set()
while stack:
key=stack[-1]
if graph[key]==[]:
stack.pop()
visit.add(key)
else:
for val in graph[key]:
if val in visit:
graph[key].remove(val)
else:
stack.append(val)
return visit

#print dfs(graph)

def recursive(graph,visit):
print len(graph),len(visit)
if len(graph)==len(visit):
print visit
return visit
#print visit
for key in graph:
#print key
if graph[key]==[] and key not in visit:
visit.add(key)
else:
for elem in graph[key]:
if elem in visit:
graph[key].remove(elem)
recursive(graph,visit)

visit=set()
print recursive(graph,visit)

DAG with loop.
loopgraph={'A':['B'],'B':['C','D','E'],'C':['A','F'],'D':[],'E':[],'F':[]}
#print loopgraph.keys()[0]
def check(stack):
visit={}
for elem in stack:
if elem not in visit:
visit[elem]=1
else:
visit[elem]+=1
count=0
for key in visit:
if visit[key]==2:
count+=1
if count==len(visit):
return True
return False

def findloop(graph):
stack=[graph.keys()[0]]
visit=set()
while stack:
if check(stack):
return True
top=stack[-1]
if graph[top]==[]:
stack.pop()
visit.add(top)
else:
for val in graph[top]:
if val in visit:
graph[top].remove(val)
else:
stack.append(val)
return False
#print findloop(loopgraph)


can be done with iterative method.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs python