From 919668176fd2ec1b8b0e5d1d093746bb145141c3 Mon Sep 17 00:00:00 2001 From: ashu9335 <115342974+ashu9335@users.noreply.github.com> Date: Sun, 29 Oct 2023 21:46:36 +0545 Subject: [PATCH] Create Find the shortest path in an unweighted graph --- Find the shortest path in an unweighted graph | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Find the shortest path in an unweighted graph diff --git a/Find the shortest path in an unweighted graph b/Find the shortest path in an unweighted graph new file mode 100644 index 0000000..2d8f9e4 --- /dev/null +++ b/Find the shortest path in an unweighted graph @@ -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}")