AlgoMaster Logo

Shortest Path in a Grid with Obstacles Elimination

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. BFS with State Tracking

Intuition:

The problem requires finding the shortest path in a grid while overcoming obstacles with a limited number of eliminations allowed for obstacles. A natural approach to explore all possible paths in an unweighted grid and account for the obstacle eliminations is to use Breadth-First Search (BFS).

In this solution:

  • We treat the grid as a graph where each cell is a node.
  • Edges exist between each node (cell) to its neighbor nodes (adjacent cells).
  • We incorporate additional state variables in our search to account for the number of eliminations performed so far and only proceed if doing so does not exceed the maximum allowable eliminations.
  • We use a 3D boolean array to track visited states, ensuring that we do not process the same state multiple times unnecessarily.

Code:

2. Optimized BFS using A* Heuristic

Intuition:

This approach enhances the BFS by adding an A* heuristic to prioritize the exploration of paths that seem promising, based on a heuristic function that estimates the cost to reach the destination. The heuristic used can be the Manhattan distance to the bottom-right corner. By incorporating the A* heuristic, we guide the BFS to expand nodes that are likely part of the shortest path, potentially reducing the number of states we explore.

Code: