Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Create Find the shortest path in an unweighted graph #54

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Find the shortest path in an unweighted graph
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from collections import defaultdict, deque

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected graph

def shortest_path(self, start, end):
if start not in self.graph or end not in self.graph:
return None

visited = set()
queue = deque()
parent = {}

queue.append(start)
visited.add(start)

while queue:
node = queue.popleft()
if node == end:
# Reconstruct the path from end to start
path = [end]
while node != start:
node = parent[node]
path.append(node)
path.reverse()
return path

for neighbor in self.graph[node]:
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = node
queue.append(neighbor)

return None

# Example usage:
g = Graph()
g.add_edge("A", "B")
g.add_edge("A", "C")
g.add_edge("B", "D")
g.add_edge("C", "E")
g.add_edge("D", "F")
g.add_edge("E", "F")

start_node = "A"
end_node = "F"
shortest_path = g.shortest_path(start_node, end_node)

if shortest_path:
print(f"Shortest path from {start_node} to {end_node}: {' -> '.join(shortest_path)}")
else:
print(f"No path found from {start_node} to {end_node}")