Answers for "breadth first search graph python"

1

breadth first search python

"""
breadFirstSearch method traverses a tree using
the Breadth-first search approach storing
its node values in an array and then
returns the resulting array.
"""
class Node:
    def __init__(self, value):
        self.value = value
        self.children = []

    def breadFirstSearch(self, array):
        queue = [self]
        while len(queue) > 0:
            current = queue.pop(0)
            array.append(current.value)
            for child in current.children:
                queue.append(child)
        return array
Posted by: Guest on April-26-2022
1

breadth first search graph python

def bfs(node):
    """ graph breadth-first search - iterative """
    from collections import deque
    
    q = deque()
    q.append(node)
    node.visited = True
    
    while q:
        current = d.popleft()
        print(current)  
            
        for node in current.adjList:
            if not node.visited: 
                q.append(node)
                node.visited = True
Posted by: Guest on March-25-2022

Code answers related to "breadth first search graph python"

Python Answers by Framework

Browse Popular Code Answers by Language