-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum Obstacle Removal to Reach Corner
32 lines (30 loc) · 1.17 KB
/
Minimum Obstacle Removal to Reach Corner
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int minimumObstacles(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] distance = new int[m][n];
for (int[] row : distance) Arrays.fill(row, Integer.MAX_VALUE);
Deque<int[]> dq = new ArrayDeque<>();
distance[0][0] = 0;
dq.offerFirst(new int[] {0, 0});
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!dq.isEmpty()) {
int[] cell = dq.pollFirst();
int x = cell[0], y = cell[1];
for (int[] dir : directions) {
int nx = x + dir[0], ny = y + dir[1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
int newDist = distance[x][y] + grid[nx][ny];
if (newDist < distance[nx][ny]) {
distance[nx][ny] = newDist;
if (grid[nx][ny] == 0) {
dq.offerFirst(new int[] {nx, ny});
} else {
dq.offerLast(new int[] {nx, ny});
}
}
}
}
}
return distance[m-1][n-1];
}
}