Page 1 of 1

Breadth First Search Graph Based Pathfinding (Find shortest distance between two graph points)

Posted: Wed Jun 09, 2021 4:10 am
by henvu50
Code to find the shortest distance between any of these two points. can be customized.
Image

Code: Select all


# look at image above. Now look at the graph below. 
# A leads to B, E, C... ........
# E leads to A, B, D.... and so on... now you know how to customize it to your liking
define graph = {'A': ['B', 'E', 'C'],
        'B': ['A', 'D', 'E'],
        'C': ['A', 'F', 'G'],
        'D': ['B', 'E'],
        'E': ['A', 'B', 'D'],
        'F': ['C'],
        'G': ['C']}

init python:

    def BFS_SP(graph, start, goal):
        explored = []

        queue = [[start]]

        if start == goal:
            return

        while queue:
            path = queue.pop(0)
            node = path[-1]

            if node not in explored:
                neighbours = graph[node]

                for neighbour in neighbours:
                    new_path = list(path)
                    new_path.append(neighbour)
                    queue.append(new_path)

                    if neighbour == goal:
                        return new_path
                explored.append(node)


label findDistanceBetweenTwoGraphPoints:

    #how to use it
    $ test34 = BFS_SP(graph, 'A', 'D')
    $ test34 = "".join(test34)
     #output the shortest distance, it will show A B D	
    "[test34]"