def DFS(graph,s):
st = []
st.append(s)
seen = set()
seen.add(s)
while st:
vertex = st.pop() #此时栈顶元素出栈
datas = graph[vertex]
for data in datas:
if data not in seen:
seen.add(data)
st.append(data)
print(vertex)
def BFS(graph,s):
que = []
que.append(s)
seen = set()
seen.add(s)
while que:
vertex = que.pop(0) #此时队头元素出队
datas = graph[vertex]
for data in datas:
if data not in seen:
seen.add(data)
que.append(data)
print(vertex)
graph={
'A':['B','C'],
'B':['A','C','D'],
'C':['A','B','D','E'],
'D':['B','C','E','F'],
'E':['C','D'],
'F':['D']
}
DFS(graph,'A')
print('----------')
BFS(graph,'A')
参考:https://blog.csdn.net/weizhifei1234/article/details/88787352