-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathucs.py
More file actions
34 lines (34 loc) · 907 Bytes
/
ucs.py
File metadata and controls
34 lines (34 loc) · 907 Bytes
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
import heapq
def uniform_cost_search(graph, start, goal):
# Priority queue to store (cost, node, path)
pq = [(0, start, [])] # (cumulative cost, current node, path)
visited = set()
while pq:
cost, node, path = heapq.heappop(pq) # Get node with the lowest cost
if node in visited:
continue
visited.add(node)
path = path + [node]
# Goal test
if node == goal:
print(f"Optimal Path: {' -> '.join(path)}, Total Cost: {cost}")
return path, cost
# Explore neighbors
for neighbor, edge_cost in graph.get(node, []):
if neighbor not in visited:
heapq.heappush(pq, (cost + edge_cost, neighbor, path))
print("Goal not reachable.")
return None, float('inf')
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('D', 2), ('E', 5)],
'C': [('F', 3)],
'D': [('G', 1)],
'E': [('G', 2)],
'F': [('G', 5)],
'G': []
}
start_node = 'A'
goal_node = 'G'
print("Uniform Cost Search Result:")
uniform_cost_search(graph, start_node, goal_node)