Sponsored
Sponsored
This approach uses a priority queue (or deque) to implement a modified Dijkstra's algorithm to explore the grid in a way similar to the 0-1 BFS (Breadth-First Search). Here, obstacles count as 'cost', and we try to find the minimum 'cost' path from the top-left corner to the bottom-right corner. We assign a priority based on the number of obstacles removed.
Time Complexity: O(m * n)
Space Complexity: O(m * n)
1from collections import deque
2
3def minimum_obstacles(grid):
4 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
5 m, n = len(grid), len(grid[0])
6 dist = [[float('inf')] * n for _ in range(m)]
7 dist[0][0] = 0
8 dq = deque([(0, 0)])
9
10 while dq:
11 x, y = dq.popleft()
12 for dx, dy in directions:
13 nx, ny = x + dx, y + dy
14 if 0 <= nx < m and 0 <= ny < n:
15 cost = dist[x][y] + grid[nx][ny]
16 if cost < dist[nx][ny]:
17 dist[nx][ny] = cost
18 if grid[nx][ny] == 0:
19 dq.appendleft((nx, ny))
20 else:
21 dq.append((nx, ny))
22 return dist[-1][-1]
The function initiates a deque with the starting point (0, 0). We use a distance array to store the minimum number of obstacles needed to reach each cell. Using directions for the four possible moves, we attempt moving to adjacent cells, leveraging the property of a deque to prioritize uncosted moves (moves to a 0) via appendleft
. In contrast, costly moves (moves to a 1) are added normally with append
. The algorithm continues until the target cell is reached with the minimum obstacle count possible.
In this approach, we utilize dynamic programming combined with a monotonic queue to solve the problem of reaching the bottom-right corner with minimal obstacle removal. This alternative method involves leveraging the properties of dynamic arrays to store and update minimal removal costs dynamically while using a queue to maintain an effective processing order based on current state values.
Time Complexity: O(m * n)
Space Complexity: O(m * n)
1from collections import deque
This dynamic programming version utilizes a monotonic queue to keep the process smooth, in essence maintaining timeline-line transitions amidst evolved states. Adjustments are made based on evaluated costs for obstacles, ensuring ultimately reaching the target state with minimal burdensome path choices.