python实现图的DFS和BFS

python实现图的DFS和BFS

img

DFS:

#定义一个图的结构
graph={
    'A':['B','C'],
    'B':['A','C','D'],
    'C':['A','B','D','E'],
    'D':['B','C','E','F'],
    'E':['C','D'],
    'F':['D']
}
def DFS(graph,s):
    stack=[s]
    seen={s}#检验是否遍历过
    while 1:
        if len(stack) > 0:
            index = stack.pop()
            for i in graph[index]:
                if i not in seen:
                    stack.append(i)
                    seen.add(i)
            print(index)
        else:break
DFS(graph,"A")

BFS:

#定义一个图的结构
graph={
    'A':['B','C'],
    'B':['A','C','D'],
    'C':['A','B','D','E'],
    'D':['B','C','E','F'],
    'E':['C','D'],
    'F':['D']
}
def BFS(graph,s):
    queue=[s]
    seen={s}#检验是否遍历过
    while 1:
        if len(queue) > 0:
            index = queue.pop(0)
            for i in graph[index]:
                if i not in seen:
                    queue.append(i)
                    seen.add(i)
            print(index)
        else:break
BFS(graph,"A")

所以,bfs和dfs的代码区别仅仅在于一个是栈顶出一个是队列出????迷惑行为

posted @ 2020-10-11 15:21  LUcKy_wA  阅读(64)  评论(0编辑  收藏