Answers for "python depth-first search non-recursive"

0

python depth-first search non-recursive

def dfs_iterative(graph, start):
    stack, path = [start], []

    while stack:
        vertex = stack.pop()
        if vertex in path:
            continue
        path.append(vertex)
        for neighbor in graph[vertex]:
            stack.append(neighbor)

    return path


adjacency_matrix = {1: [2, 3], 2: [4, 5],
                    3: [5], 4: [6], 5: [6],
                    6: [7], 7: []}

print(dfs_iterative(adjacency_matrix, 1))
# [1, 3, 5, 6, 7, 2, 4]
Posted by: Guest on October-26-2021

Code answers related to "python depth-first search non-recursive"

Python Answers by Framework

Browse Popular Code Answers by Language