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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值