Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 27, 2021 03:48 am GMT

Graph Traversal in Python

Let's say we have the following graph:

graph = {    5: [3, 7],    3: [2, 1],    7: [8],    2: [],    1: [],    8: []}

There are two ways to traverse this graph
-> Breadth First Search (BFS)
-> Depth First Search (DFS)

BFS can be imagined as horizontal neighbours and DFS can be imagined as vertical neighbours.

Implementation of BFS:

def bfs(graph, node, path=[]):    queue = [node]    while queue:        node = queue.pop(0)        if node not in queue:            path.append(node)            for neighbour in graph[node]:                queue.append(neighbour)    return path

Output:

>>> bfs(graph, 5)    [5, 3, 7, 2, 1, 8]

Implementation of DFS:

def dfs(graph, node, path=[]):    queue = set()    if node not in queue:        queue.add(node)        path.append(node)        for neighbour in graph[node]:            path = dfs(graph, neighbour)    return path

Output:

>>> dfs(graph, 5)    [5, 3, 2, 1, 7, 8]

Original Link: https://dev.to/sbalasa/graph-traversal-in-python-1944

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To