I have a directed network as follows.
Now, I would like to get all the possible 4 length and 5 length paths of this graph (where both the starting and ending paths are B)
Examples of 4 length paths are;
- B--C--B--A--B
- B--A--B--B--B
- B--A--B--C--B
Examples of 5 length paths are;
- B--C--B--A--B--B
- B--A--B--B--C--B
I tried to use Breadth First Search (BFS) to solve this. It seems like most of the code of BFS algorithm does not satisfies my requirements. That is;
- They do not consider variable length paths
- Their starting and end node is not same as mine (They are different)
My current code is as follows:
graph = {'A': ['B'],
'B': ['A','C', 'B'],
'C': ['B']}
# visits all the nodes of a graph (connected component) using BFS
def bfs_connected_component(graph, start):
# keep track of all visited nodes
explored = []
# keep track of nodes to be checked
queue = [start]
# keep looping until there are nodes still to be checked
while queue:
# pop shallowest node (first node) from queue
node = queue.pop(0)
if node not in explored:
# add node to list of checked nodes
explored.append(node)
neighbours = graph[node]
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
return explored
bfs_connected_component(graph,'A')
I would like to know if there are any python libraries I can use for this or is there is a way to modify BFS to accomplish this problem.
I am happy to provide more examples if needed :)