DEV Community

Nazim Shaikh
Nazim Shaikh

Posted on

A* SEARCH ALGORITHM IN PYTHON

INTRODUCTION

Pathfinding is an important concept in computer science and Artificial Intelligence. It is used to find a route between two locations while avoiding obstacles.

The A* (A-Star) Search Algorithm is a popular pathfinding algorithm used in games, robotics and navigation systems.

WHAT IS THE A* SEARCH ALGORITHM?

A* is an informed search algorithm that finds a minimum-cost path from a starting point to a destination under suitable conditions.

It uses two important values:

  • g(n): Actual cost from the starting point to the current node.
  • h(n): Estimated cost from the current node to the destination.

MATHEMATICAL FORMULA

f(n) = g(n) + h(n)

The algorithm explores the node with the lowest estimated total cost.

HOW DOES IT WORK?

  1. Define the starting and destination points.
  2. Create a grid containing empty cells and obstacles.
  3. Calculate the estimated distance to the destination.
  4. Explore neighbouring cells.
  5. Avoid cells containing obstacles.
  6. Continue until the destination is reached.
  7. Reconstruct the final path.

PYTHON IMPLEMENTATION

Python Code:

import heapq

def heuristic(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])


def astar(grid, start, goal):

    rows = len(grid)
    cols = len(grid[0])

    open_list = []
    heapq.heappush(
        open_list,
        (heuristic(start, goal), start)
    )

    came_from = {}
    g_score = {start: 0}

    directions = [
        (0, 1), (0, -1),
        (1, 0), (-1, 0)
    ]

    while open_list:

        _, current = heapq.heappop(open_list)

        if current == goal:
            path = []

            while current in came_from:
                path.append(current)
                current = came_from[current]

            path.append(start)
            return path[::-1]

        for dr, dc in directions:

            neighbor = (
                current[0] + dr,
                current[1] + dc
            )

            r, c = neighbor

            if not (0 <= r < rows and 0 <= c < cols):
                continue

            if grid[r][c] == 1:
                continue

            new_cost = g_score[current] + 1

            if new_cost < g_score.get(
                neighbor, float('inf')
            ):

                came_from[neighbor] = current
                g_score[neighbor] = new_cost

                f_score = (
                    new_cost + heuristic(neighbor, goal)
                )

                heapq.heappush(
                    open_list,
                    (f_score, neighbor)
                )

    return None


# 0 = Free cell
# 1 = Obstacle

grid = [
    [0, 0, 0, 0],
    [1, 1, 0, 1],
    [0, 0, 0, 0],
    [0, 1, 1, 0]
]

start = (0, 0)
goal = (3, 3)

path = astar(grid, start, goal)

print("Shortest Path:", path)
Enter fullscreen mode Exit fullscreen mode

OUTPUT

Shortest Path:
[(0, 0), (0, 1), (0, 2),
 (1, 2), (2, 2), (2, 3), (3, 3)]
Enter fullscreen mode Exit fullscreen mode

The algorithm finds a path while avoiding blocked cells.

APPLICATIONS

  1. Video game navigation.
  2. Robot pathfinding.
  3. GPS navigation systems.
  4. Maze-solving applications.
  5. Autonomous navigation.
  6. Route planning.

ADVANTAGES

  • Finds an optimal path under suitable conditions.
  • Uses heuristic information to guide the search.
  • Avoids blocked cells.
  • Useful for grid-based navigation.

LIMITATIONS

  • Can consume considerable memory.
  • Performance depends on the heuristic function.
  • Large search spaces can increase computation time.

CONCLUSION

A* Search is a powerful pathfinding algorithm that combines actual movement cost and estimated distance to find an efficient route. It is widely used in robotics, games and navigation systems.

Top comments (0)