Breadth-First Search Shortest Path Finder Using Graph-tool

  • Share this:

Code introduction


This function uses the breadth_first_search function from the Graph-tool library to find the shortest path in a graph from the source node to the target node.


Technology Stack : Graph-tool, breadth_first_search

Code Type : Graph-tool algorithm application

Code Difficulty : Intermediate


                
                    
def find_shortest_path(graph, source, target):
    import graph_tool.all as gt
    from graph_tool.search import breadth_first_search

    # Create a breadth-first search object
    bfs = breadth_first_search(graph, root=source, target=target)

    # Get the path from source to target
    path = bfs.get_path(target)

    return path