def DFS(graph,s):
stack=[]
stack.append(s)
data=[]
data.append(s)
while stack:
n=stack.pop()
nodes=graph[n]
for i in nodes[::-1]:
if i not in data:
stack.append(i)
data.append(i)
print(n)
def BFS(graph,q):
queue=[]
queue.append(q)
data=[]
data.append(q)
while queue:
n=queue.pop(0)
nodes=graph[n]
for j in nodes:
if j not in data:
queue.append(j)
data.append(j)
print(n)
if __name__ == '__main__':
graph={
'1':['2','3'],
'2':['4','5'],
'3':['6','7'],
'4':['8'],
'5':['8'],
'6':['7'],
'7':[],
'8':[],
}
print("深度优先遍历:")
DFS(graph,'1')
print("广度优先遍历:")
BFS(graph,'1')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)