This repository has been archived by the owner on Sep 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
travelling_salesman_bfs.py
76 lines (63 loc) · 1.97 KB
/
travelling_salesman_bfs.py
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
68
69
70
71
72
73
74
75
76
"""
Write python code for Traveling Salesman Problem (TSP) using Breadth First Search
(BFS). Graph Given Below.
graph = {
'A': {'B': 2, 'C': 3, 'D': 1},
'B': {'A': 2, 'C': 4, 'D': 2},
'C': {'A': 3, 'B': 4, 'D': 3},
'D': {'A': 1, 'B': 2, 'C': 3}
}
"""
class Deque:
def __init__(self):
self.arr = []
def enqueue(self, ele):
self.arr.append(ele)
def dequeue(self):
return self.arr.pop(0)
def __str__(self):
res = "Queue: "
for ele in self.arr:
res += str(ele) + " "
return res
class Graph:
def __init__(self, adjlist : dict = {}):
self.adj = adjlist
def __str__(self):
res = ""
for tail, headlist in self.adj.items():
for head in headlist:
res += f"({tail} -> {head}, {headlist[head]})\t"
res += "\n"
return res
def bfs(self, start):
queue = Deque()
queue.enqueue((start, [start]))
while queue.arr:
(node, path) = queue.dequeue()
for next_node in set(self.adj[node]) - set(path):
if len(path) + 1 == len(self.adj):
yield path + [next_node]
else:
queue.enqueue((next_node, path + [next_node]))
def tsp_bfs(self, start):
shortest_path = None
shortest_path_length = float('inf')
for path in self.bfs(start):
path_length = sum(self.adj[path[i-1]][path[i]] for i in range(len(path)))
if path_length < shortest_path_length:
shortest_path = path
shortest_path_length = path_length
return shortest_path, shortest_path_length
if __name__ == "__main__":
graph = {
'A': {'B': 2, 'C': 3, 'D': 1},
'B': {'A': 2, 'C': 4, 'D': 2},
'C': {'A': 3, 'B': 4, 'D': 3},
'D': {'A': 1, 'B': 2, 'C': 3}
}
g = Graph(graph)
print(g.tsp_bfs('C'))
"""
(['C', 'B', 'A', 'D'], 10)
"""