#1293

Shortest Path in a Grid with Obstacles Elimination

Hard
ArrayBreadth-First SearchMatrixBreadth-First SearchDynamic Programming
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution uses Breadth-First Search (BFS) to explore the grid while keeping track of the number of obstacles eliminated. This approach ensures that we find the shortest path efficiently by exploring all possible paths level by level.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue for BFS and a 3D visited array to track visited cells with the number of obstacles eliminated.
  2. 2Step 2: Start from the top-left corner (0, 0) and enqueue it with the initial steps and remaining k.
  3. 3Step 3: While the queue is not empty, dequeue an element and explore its neighbors (up, down, left, right). If a neighbor is an obstacle and we can eliminate it, enqueue it with updated steps and remaining k.
solution.py23 lines
1# Full working Python code
2from collections import deque
3
4def min_steps(grid, k):
5    m, n = len(grid), len(grid[0])
6    visited = [[[False] * (k + 1) for _ in range(n)] for _ in range(m)]
7    queue = deque([(0, 0, 0, k)])  # (x, y, steps, remaining_k)
8    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
9
10    while queue:
11        x, y, steps, remaining_k = queue.popleft()
12        if x == m - 1 and y == n - 1:
13            return steps
14        for dx, dy in directions:
15            nx, ny = x + dx, y + dy
16            if 0 <= nx < m and 0 <= ny < n:
17                if grid[nx][ny] == 0 and not visited[nx][ny][remaining_k]:
18                    visited[nx][ny][remaining_k] = True
19                    queue.append((nx, ny, steps + 1, remaining_k))
20                elif grid[nx][ny] == 1 and remaining_k > 0 and not visited[nx][ny][remaining_k - 1]:
21                    visited[nx][ny][remaining_k - 1] = True
22                    queue.append((nx, ny, steps + 1, remaining_k - 1))
23    return -1

Complexity note: The time complexity is O(m * n * k) because we may visit each cell with each possible number of obstacles eliminated. The space complexity is also O(m * n * k) due to the visited array.

  • 1Using BFS allows us to explore all possible paths efficiently without revisiting cells unnecessarily.
  • 2Tracking the number of obstacles eliminated helps in making optimal decisions at each step.

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