Skip to content

Commit b3806d4

Browse files
Merge pull request #11 from ahmedabougabal/a_star_algo
Feat(algo): Implements A* Search algorithm for detecting the best and…
2 parents ce17578 + 0fe04ac commit b3806d4

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from priority_queue import PriorityQueue
2+
3+
from helpers import offsets, create_maze, is_legal_pos, get_path
4+
5+
def heuristic(a, b): # this is what makes this algorithm more effecicent than Dijkstra algo
6+
x1,y1 = a
7+
x2, y2 = b
8+
return abs(x1 - x2) + abs(y1 - y2)
9+
10+
11+
def print_maze_with_path(maze, path):
12+
for i in range(len(maze)):
13+
for j in range(len(maze[0])):
14+
if(i, j) in path:
15+
print("* ", end="")
16+
else:
17+
print(f"{maze[i][j]}", end= "")
18+
print()
19+
20+
21+
#* g value is the cost from the start to current
22+
def a_star(maze, start, goal):
23+
pq = PriorityQueue()
24+
predecessor = {start:None}
25+
g_values = {start: 0}
26+
pq.put(start,0)
27+
28+
while not pq.is_empty():
29+
current = pq.get()
30+
if current == goal:
31+
return get_path(predecessor, start, goal)
32+
33+
for direction in ["up", "right", "down", "left"]:
34+
x, y = offsets[direction]
35+
neighbour = (current[0] + x , current[1]+y)
36+
37+
if is_legal_pos(maze, neighbour) and neighbour not in g_values:
38+
g_tentative = g_values[current] + 1
39+
g_values[neighbour] = g_tentative
40+
f_value = g_tentative + heuristic(goal, neighbour)
41+
pq.put(neighbour, f_value)
42+
predecessor[neighbour] = current
43+
44+
return None
45+
46+
47+
# testing
48+
if __name__ == "__main__":
49+
50+
myMaze = create_maze();
51+
# Find and print path
52+
start = (0, 0)
53+
goal = (3, 3)
54+
path = a_star(myMaze, start, goal)
55+
56+
if path:
57+
print("Path found!")
58+
print("Path coordinates:", path)
59+
print("\nMaze with path marked (*):")
60+
print_maze_with_path(myMaze, path) # Fixed: Don't print the function itself
61+
else:
62+
print("No path found!")
63+

0 commit comments

Comments
 (0)