From bdad0277b874b35da54ce954e3b7b662afa3faba Mon Sep 17 00:00:00 2001 From: Sarvesh Dubey <38752758+dubesar@users.noreply.github.com> Date: Fri, 10 May 2019 08:36:46 +0530 Subject: [PATCH 1/2] Created shortest path using bfs --- graphs/bfs-shortestpath.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 graphs/bfs-shortestpath.py diff --git a/graphs/bfs-shortestpath.py b/graphs/bfs-shortestpath.py new file mode 100644 index 000000000000..6064629a434a --- /dev/null +++ b/graphs/bfs-shortestpath.py @@ -0,0 +1,35 @@ +def bfs_shortest_path(graph, start, goal): + # keep track of explored nodes + explored = [] + # keep track of all the paths to be checked + queue = [[start]] + + # return path if start is goal + if start == goal: + return "That was easy! Start = goal" + + # keeps looping until all possible paths have been checked + while queue: + # pop the first path from the queue + path = queue.pop(0) + # get the last node from the path + node = path[-1] + if node not in explored: + neighbours = graph[node] + # go through all neighbour nodes, construct a new path and + # push it into the queue + for neighbour in neighbours: + new_path = list(path) + new_path.append(neighbour) + queue.append(new_path) + # return path if neighbour is goal + if neighbour == goal: + return new_path + + # mark node as explored + explored.append(node) + + # in case there's no path between the 2 nodes + return "So sorry, but a connecting path doesn't exist :(" + +bfs_shortest_path(graph, 'G', 'D') # returns ['G', 'C', 'A', 'B', 'D'] From 57602fac3528f33ba57e606f7aafd30de8c36ba9 Mon Sep 17 00:00:00 2001 From: Sarvesh Dubey <38752758+dubesar@users.noreply.github.com> Date: Sun, 12 May 2019 09:47:46 +0530 Subject: [PATCH 2/2] added graph dictionary --- graphs/bfs-shortestpath.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/graphs/bfs-shortestpath.py b/graphs/bfs-shortestpath.py index 6064629a434a..5853351a53a3 100644 --- a/graphs/bfs-shortestpath.py +++ b/graphs/bfs-shortestpath.py @@ -1,3 +1,11 @@ +graph = {'A': ['B', 'C', 'E'], + 'B': ['A','D', 'E'], + 'C': ['A', 'F', 'G'], + 'D': ['B'], + 'E': ['A', 'B','D'], + 'F': ['C'], + 'G': ['C']} + def bfs_shortest_path(graph, start, goal): # keep track of explored nodes explored = []