-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_basic.py
More file actions
67 lines (54 loc) · 1.83 KB
/
graph_basic.py
File metadata and controls
67 lines (54 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for start, end in self.edges:
if start not in self.graph_dict:
self.graph_dict[start] = [end]
else:
self.graph_dict[start].append(end)
print("Graph\n\n", self.graph_dict)
def get_paths(self, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in self.graph_dict:
return []
paths = []
for node in self.graph_dict[start]:
if node not in path:
new_path = self.get_paths(node, end, path)
for p in new_path:
paths.append(p)
return paths
def get_shortest_path(self, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in self.graph_dict:
return []
short_path = None
for node in self.graph_dict[start]:
if node not in path:
sp = self.get_shortest_path(node, end, path)
if sp:
if short_path is None or len(sp) < len(short_path):
short_path = sp
return short_path
routes = [
("Mumbai","Pune"),
("Mumbai", "Surat"),
("Surat", "Bangaluru"),
("Pune","Hyderabad"),
("Pune","Mysuru"),
("Hyderabad","Bangaluru"),
("Hyderabad", "Chennai"),
("Mysuru", "Bangaluru"),
("Chennai", "Bangaluru")
]
route_graph = Graph(routes)
start = "Dublin"
end = "Bangaluru"
#Py3
print(f"All paths between: {start} and {end}: ", route_graph.get_paths(start,end))
print(f"Shortest path between: {start} and {end}: ", route_graph.get_shortest_path(start,end))