Tutorialspoint
Problem
Solution
Submissions

A* Search Algorithm for Path Finding

Certification: Advanced Level Accuracy: 50% Submissions: 2 Points: 15

Write a Python program to implement the A* search algorithm for finding the shortest path in a grid. The grid consists of obstacles (represented by '1') and free spaces (represented by '0'). Your task is to implement the find_path(grid, start, end) function, which returns the shortest path from the start point to the end point.

Example 1
  • Input: grid = [
    [0, 0, 0, 0, 1],
    [1, 1, 0, 1, 0],
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0]
    ]
    start = (0, 0) end = (4, 4)
  • Output: [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3), (2, 4), (3, 4), (4, 4)]
  • Explanation:
    • Step 1: Use A* to navigate from (0,0) to (4,4).
    • Step 2: Avoid obstacles (cells with 1).
    • Step 3: Return the optimal path based on cost and heuristic.
  • Example 2
    • Input: grid = [ [0, 0, 1, 0],
      [1, 0, 1, 0],
      [0, 0, 0, 0]
      ] start = (0, 0) end = (2, 3)
  • Output: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3)]
  • Explanation:
    • Step 1: Identify path from start to end using A*.
    • Step 2: The path makes a detour around obstacles in columns 0 and 2.
  • Constraints
    • 1 ≤ grid.length ≤ 100
    • 1 ≤ grid[0].length ≤ 100
    • grid[i][j] is either 0 (free space) or 1 (obstacle)
    • start and end coordinates are valid cells within the grid bounds
    • Time Complexity: O(n * log(n)), where n is the number of cells
    • Space Complexity: O(n)
    Priority QueueAlgorithmsAmazonTutorialspoint
    Editorial

    Login to view the detailed solution and explanation for this problem.

    My Submissions
    All Solutions
    Lang Status Date Code
    You do not have any submissions for this problem.
    User Lang Status Date Code
    No submissions found.

    Please Login to continue
    Solve Problems

     
     
     
    Output Window

    Don't have an account? Register

    Solution Hints

    • Use Manhattan distance as a heuristic function to estimate the distance from any cell to the goal
    • Implement a priority queue to efficiently select the next node with the lowest f-score
    • Keep track of visited nodes to avoid revisiting them
    • For each node, consider all valid neighbors (up, down, left, right)
    • Use a parent dictionary to reconstruct the path once the goal is reached

    Steps to solve by this approach:

     Step 1: Define a heuristic function (Manhattan distance) to estimate distance to goal
     Step 2: Initialize the open list with the start node and the closed set for visited nodes
     Step 3: While the open list is not empty, select the node with lowest f-score
     Step 4: If the current node is the goal, reconstruct and return the path
     Step 5: Otherwise, explore all valid neighbors and update their scores

    Submitted Code :