Chi Zhang
发布于 2024-07-14 / 21 阅读
0
0

DFS & BFS

DFS

recursive

DFS(graph, node, visited):
    if node not in visited:
        process(node)
        add node to visited

        for each neighbor in graph[node]:
            DFS(graph, neighbor, visited)

stack

DFS(graph, start_node):
    create a stack S
    create a set visited
    push start_node to S
    add start_node to visited

    while S is not empty:
        node = pop S
        process(node)

        for each neighbor in graph[node]:
            if neighbor not in visited:
                push neighbor to S
                add neighbor to visited

BFS

queue

BFS(graph, start_node):
    create a queue Q
    create a set visited
    enqueue start_node to Q
    add start_node to visited

    while Q is not empty:
        node = dequeue Q
        process(node)

        for each neighbor in graph[node]:
            if neighbor not in visited:
                enqueue neighbor to Q
                add neighbor to visited


评论