I am trying to implement a bi-directional search in python.
As I understand, I should somehow merge two breadth-first searches, one which starts at the starting (or root) node and one which starts at the goal (or end) node. The bi-directional search terminates when both breadth-first searches "meet" at the same vertex. I have implemented BFS the code is given below
def bfs(graph, start):
path = []
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in path:
path.append(vertex)
queue.extend(graph[vertex])
return path
Could you provide me with a code example (in Python) or link with code for the bidirectional graph search?
This seemed like a fun problem so I had a go at it. Here's my attempt. You didn't say what format your graph is in, so I guessed a dictionary like the following:
The code runs through a list of currently active vertices, starting from the specified start and goal vertices, and remembers how it got to them through a dictionary of {vertices : lists}. If an active vertex finds itself next to another active vertex with a path that started from the other end, it merges the lists and returns the results, otherwise it extends all the paths and continues.