#2290

Minimum Obstacle Removal to Reach Corner

Hard
ArrayBreadth-First SearchGraph TheoryHeap (Priority Queue)MatrixShortest PathGraph TraversalDijkstra's AlgorithmPriority Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n log(m * n))
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n log(m * n))Space O(m * n)

Using a modified Dijkstra's algorithm allows us to efficiently find the minimum number of obstacles to remove by treating the grid as a graph where moving into an obstacle has a cost of 1.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a priority queue to explore cells based on the number of obstacles removed.
  2. 2Step 2: Start from the top-left corner and push it into the queue with a cost of 0.
  3. 3Step 3: While the queue is not empty, pop the cell with the lowest cost, and explore its neighbors, updating their costs if a better path is found.
solution.py20 lines
1# Full working Python code
2import heapq
3from typing import List
4
5def min_obstacles(grid: List[List[int]]) -> int:
6    m, n = len(grid), len(grid[0])
7    pq = [(0, 0, 0)]  # (cost, x, y)
8    visited = set()
9    while pq:
10        cost, x, y = heapq.heappop(pq)
11        if (x, y) in visited:
12            continue
13        visited.add((x, y))
14        if x == m - 1 and y == n - 1:
15            return cost
16        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
17            nx, ny = x + dx, y + dy
18            if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited:
19                heapq.heappush(pq, (cost + grid[nx][ny], nx, ny))
20    return -1

Complexity note: The complexity arises from the priority queue operations, where we may need to process each cell multiple times, leading to a logarithmic factor due to the heap.

  • 1Model the grid as a graph where each cell is a node and edges represent possible moves.
  • 2Using a priority queue helps efficiently find the minimum cost path in terms of obstacles removed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.