topological sort python recursive and iterative

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.



你可能感兴趣的:(python,DFS)