bfs和dfs基础

# bfs & 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 bfs(graph,s):
    queue = []
    queue.append(s)
    seen = set()
    seen.add(s)
    while len(queue) > 0:
        vis = queue.pop(0)
        nodes = graph[vis]
        for w in nodes:
            if w not in seen:
                queue.append(w)
                seen.add(w)
        
        print(vis)
     
def dfs(graph,s):
    stack = []
    stack.append(s)
    seen = set()
    seen.add(s)
    while len(stack) > 0:
        vis = stack.pop()
        nodes = graph[vis]
        for w in nodes:
            if w not in seen:
                stack.append(w)
                seen.add(w)
        
        print(vis)   


def main():
    bfs(graph,"E")
    dfs(graph,"E")


if __name__ == "__main__":
    main()
posted @ 2022-08-25 20:32  Ray_chen  阅读(10)  评论(0编辑  收藏  举报