import heapq
def a_star(graph, start, goal):
"""
Performs A* pathfinding on a 2D grid.
Args:
graph: 2D list where 0 = walkable, 1 = obstacle.
start: Tuple (x, y) for start position.
goal: Tuple (x, y) for goal position.
Returns:
List of tuples representing the path from start to goal.
Returns None if no path is found.
"""
# 1. Define Helper Functions
def heuristic(a, b):
"""
Estimate the distance between two points.
Using Manhattan distance (abs(x_diff) + abs(y_diff))
suitable for grids with no diagonal movement.
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def get_neighbors(node):
"""Return 4-directional neighbors (Up, Down, Left, Right)."""
x, y = node
neighbors = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
valid_neighbors = []
for nx, ny in neighbors:
# Check bounds
if 0 <= ny < len(graph) and 0 <= nx < len(graph[0]):
# Check if walkable (0)
if graph[ny][nx] == 0:
valid_neighbors.append((nx, ny))
return valid_neighbors
# 2. Initialize Variables
open_set = []
heapq.heappush(open_set, (0, start))
came_from = {} # Tracks the path: child -> parent
g_score = {start: 0} # Cost from start to current node
f_score = {start: heuristic(start, goal)} # Estimated total cost
open_set_hash = {start} # Helper to check quickly if item in queue
# 3. Main Loop
while open_set:
# Get the node with the lowest f_score
current = heapq.heappop(open_set)[1]
open_set_hash.remove(current)
# Found the goal!
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1] # Return reversed path
for neighbor in get_neighbors(current):
# Cost to reach neighbor is current cost + 1 (grid distance)
tentative_g_score = g_score[current] + 1
# If this path to neighbor is better than any previous one
if tentative_g_score < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
if neighbor not in open_set_hash:
heapq.heappush(open_set, (f_score[neighbor], neighbor))
open_set_hash.add(neighbor)
return None # No path found
# --- Visualization and Usage ---
def visualize_path(grid, path, start, end):
"""Prints the grid with the path marked."""
# Create a visual copy of the grid
visual_grid = [row[:] for row in grid]
if path:
for x, y in path:
visual_grid[y][x] = '*' # Mark path
# Mark start and end specifically
visual_grid[start[1]][start[0]] = 'S'
visual_grid[end[1]][end[0]] = 'E'
print("\nGrid Result:")
print("-" * (len(grid[0]) * 2 + 1))
for row in visual_grid:
print("|" + " ".join(str(cell) for cell in row) + "|")
print("-" * (len(grid[0]) * 2 + 1))
# Define a Map: 0 = Empty, 1 = Wall
# 10x10 Grid
my_grid = [
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 0]
]
start_pos = (0, 0) # Top Left
end_pos = (9, 9) # Bottom Right
# Run Algorithm
path_result = a_star(my_grid, start_pos, end_pos)
if path_result:
print(f"Path found! Length: {len(path_result)}")
visualize_path(my_grid, path_result, start_pos, end_pos)
else:
print("No path found.")