-
Notifications
You must be signed in to change notification settings - Fork 0
/
astar-closest-path.py
94 lines (84 loc) · 3.15 KB
/
astar-closest-path.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
import numpy as np
import heapq
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def heuristic(a, b):
return np.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2)
def astar(array, start, goal):
neighbors = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
close_set = set()
came_from = {}
gscore = {start:0}
fscore = {start:heuristic(start, goal)}
oheap = []
heapq.heappush(oheap, (fscore[start], start))
while oheap:
current = heapq.heappop(oheap)[1]
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
data = data + [start]
data = data[::-1]
return data
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
tentative_g_score = gscore[current] + heuristic(current, neighbor)
if 0 <= neighbor[0] < array.shape[0]:
if 0 <= neighbor[1] < array.shape[1]:
if array[neighbor[0]][neighbor[1]] == 1:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(oheap, (fscore[neighbor], neighbor))
# If no path to goal was found, return closest path to goal
if goal not in came_from:
closest_node = None
closest_dist = float('inf')
for node in close_set:
dist = heuristic(node, goal)
if dist < closest_dist:
closest_node = node
closest_dist = dist
if closest_node is not None:
data = []
while closest_node in came_from:
data.append(closest_node)
closest_node = came_from[closest_node]
data = data + [start]
data = data[::-1]
return data
return False
def visualize_path(matris, path):
matris_with_path = np.copy(matris)
for point in path:
matris_with_path[point[0], point[1]] = 2 # Assign a unique value for the path
cmap = ListedColormap(['white', 'black', 'red']) # 0: white, 1: black, 2: red
plt.imshow(matris_with_path, cmap=cmap, interpolation='nearest')
plt.title('Matrix and Path (Closest Path to Goal if no Path Found)')
plt.show()
def main():
matris = np.random.choice([0, 1], size=(10, 10))
start = (0, 0)
goal = (9, 9)
path = astar(matris, start, goal)
if path:
print("Path found")
visualize_path(matris, path)
print(path)
else:
print("No path found")
if __name__ == '__main__':
main()