codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Algorithms] BFS and DFS through a graph #33

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

Prompt: Traverse through a graph using BFS and DFS. You can either do this iteratively or recursively.

cs-cordero commented 5 years ago
from collections import deque

def bfs(root: Node):
    queue = deque([root])
    while queue:
        node = queue.popleft()
        # do stuff with node
        queue.extend(node.children)

def dfs(node: Node):
    for child in node.children:
        dfs(child)