-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAstar.py
104 lines (90 loc) · 2.42 KB
/
Astar.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import sys
class Graph:
def __init__(self):
self.adjDict = dict()
self.start_node = "S"
self.goal_node = "S"
self.heuristics = dict()
def add_edge(self, u, v, w):
if u not in self.adjDict:
self.adjDict[u] = list()
self.adjDict[u].append([v, w])
def add_heuristic(self, node, val):
self.heuristics[node] = val
def print(self):
for key in self.adjDict:
print(key)
print(self.adjDict[key])
def set_start_node(self, node):
self.start_node = node
def set_goal_node(self, node):
self.goal_node = node
def astar(self):
max_distance = sys.maxsize
q = list()
fx = self.heuristics[self.start_node] + 0
q.append([fx, self.start_node])
while q:
pair = q.pop(0)
fx = pair[0]
node = pair[1]
dist_so_far = fx - self.heuristics[node]
if node == self.goal_node:
if dist_so_far < max_distance:
max_distance = dist_so_far
children = []
if node in self.adjDict:
children = self.adjDict[node]
for edge in children:
child = edge[1]
weight = edge[0]
q.append([dist_so_far + weight + self.heuristics[child], child])
q.sort()
print(f"min distance to goal node is {max_distance}")
def main():
print("enter input")
graph = Graph()
while True:
tokens = input().split()
parent = tokens[0]
if parent == "-1":
break
children = tokens[1:]
for child in children:
# print(child)
# print(child.split(","))
graph.add_edge(parent, int(
child.split(",")[1]), child.split(",")[0])
while True:
tokens = input().split()
node = tokens[0]
if node == "-1":
break
value = int(tokens[1])
graph.add_heuristic(node, value)
# print(graph.adjDict)
# print(graph.heuristics)
# graph.print()
start_node = input("enter start node: ")
goal_node = input("enter goal node: ")
graph.set_start_node(start_node)
graph.set_goal_node(goal_node)
graph.astar()
main()
'''
enter input
S A,1 B,4
A B,2 C,5 D,12
B C,2
C D,3
-1
S 7
A 6
B 2
C 1
D 0
-1
enter start node: S
enter goal node: D
min distance to goal node is 8
'''