Skip to content

Instantly share code, notes, and snippets.

@yjzhang
Created September 29, 2022 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjzhang/2d2e68e916e679a5037828b644223864 to your computer and use it in GitHub Desktop.
Save yjzhang/2d2e68e916e679a5037828b644223864 to your computer and use it in GitHub Desktop.
Find all shortest paths between two nodes in a graph using BFS.
def find_all_shortest_paths(dic_node, n1, n2, step_threshold):
return_paths = []
visit_queue = [[n1]]
# this can be updated to get all shortest paths for all visited nodes
# for the shortest path from N1 to N2, all intermediate paths are also shortest paths between their respective nodes.
visited_nodes_prev = set()
visited_nodes = set()
cur_distance = 0
while len(visit_queue):
cur_path = visit_queue.pop(0)
if len(cur_path) >= step_threshold:
break
# update shortest paths
if len(cur_path) > cur_distance:
cur_distance = len(cur_path)
visited_nodes.update(visited_nodes_prev)
cur = cur_path[-1]
if cur in dic_node:
for node2 in dic_node[cur]:
if node2 in visited_nodes:
continue
if node2 == n2:
return_paths.append(cur_path + [node2,])
step_threshold = len(cur_path) + 1
else:
visit_queue.append(cur_path + [node2,])
visited_nodes_prev.add(node2)
return return_paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment