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
/
Copy pathucs_q3.py
66 lines (50 loc) · 1.83 KB
/
ucs_q3.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
class PriorityQueue:
def __init__(self):
self.queue = []
def insert(self, priority, item):
self.queue.append((priority, item))
self.queue.sort(reverse=True)
def extract_min(self):
if not self.queue:
return None
return self.queue.pop()[1]
def is_empty(self):
return len(self.queue) == 0
class Graph:
def __init__(self, adjlist):
self.adj = adjlist
def neighbors(self, node):
return self.adj[node]
def uniform_cost_search(graph, start, goal):
frontier = PriorityQueue()
frontier.insert(0, (start, [], 0)) # Priority is the cost of the path
explored = set()
while not frontier.is_empty():
current_node, path, cost = frontier.extract_min()
if current_node == goal:
return cost, path + [current_node]
explored.add(current_node)
for neighbor, neighbor_cost in graph.neighbors(current_node).items():
if neighbor not in explored:
new_cost = cost + neighbor_cost
frontier.insert(new_cost, (neighbor, path + [current_node], new_cost))
return None, None
if __name__ == "__main__":
graph = {
'maldon':{'tiptree': 8},
'tiptree':{'feering': 3, 'clacton': 29},
'feering':{'maldon': 11, 'blaxhali': 46},
'clacton':{'maldon': 40, 'harwich': 17},
'harwich':{'tiptree': 31, 'blaxhali': 40, 'dunwich': 53},
'blaxhali':{'dunwich': 15},
'dunwich':{'blaxhali': 17},
}
g = Graph(graph)
start_node = 'maldon'
goal_node = 'dunwich'
min_cost, path = uniform_cost_search(g, start_node, goal_node)
if path:
print("Best path from", start_node, "to", goal_node, ":", path)
print("Minimum cost:", min_cost)
else:
print("No path found from", start_node, "to", goal_node)