Created
December 7, 2023 21:05
-
-
Save PeterWaIIace/3f110e647f5a8afd9484596eaac5dd4d to your computer and use it in GitHub Desktop.
Find shortest path in unbalanced graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from queue import Queue | |
def shortest_path(graph, start_node, end_node): | |
visited = set() | |
q = Queue() | |
# (current_node, path) | |
q.put((start_node,[start_node])) | |
while q.qsize(): | |
curr_node, path = q.get() | |
print(curr_node, path) | |
if curr_node == end_node: | |
return path | |
if curr_node not in visited: | |
visited.add(curr_node) | |
for next_node in graph[curr_node]: | |
q.put((next_node,path + [next_node])) | |
# Example graph as an adjacency list | |
graph = { | |
'A': ['B'], | |
'B': ['A', 'C', 'E'], | |
'C': ['B', 'F'], | |
'D': ['A'], | |
'E': ['B', 'F'], | |
'F': ['C', 'E'] | |
} | |
# Print the entire graph | |
print("Graph:") | |
start_node = 'A' | |
end_node = 'F' | |
result_path = shortest_path(graph, start_node, end_node) | |
print(f"\nShortest path from {start_node} to {end_node}: {result_path}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment