Skip to content

Commit 5983472

Browse files
committed
Time: 145 ms (38.13%), Space: 83.3 MB (10.93%) - LeetHub
1 parent 025f2e5 commit 5983472

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public int minimumObstacles(int[][] grid) {
3+
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[2] - b[2]);
4+
int[][] dir = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
5+
int m = grid.length, n = grid[0].length;
6+
int[][] count = new int[m][n];
7+
for(int i = 0;i < m;i++) {
8+
Arrays.fill(count[i], Integer.MAX_VALUE);
9+
}
10+
count[0][0] = 0;
11+
q.offer(new int[]{0, 0, 0});
12+
while(!q.isEmpty()) {
13+
int[] cur = q.poll();
14+
int x = cur[0];
15+
int y = cur[1];
16+
int cost = cur[2];
17+
if(x == m - 1 && y == n - 1) {
18+
return cost;
19+
}
20+
for(int i = 0;i < 4;i++) {
21+
int nx = x + dir[i][0];
22+
int ny = y + dir[i][1];
23+
if(nx < 0 || ny < 0 || nx >= m || ny >= n) {
24+
continue;
25+
}
26+
int now = cur[2];
27+
if(grid[nx][ny] == 1) {
28+
now++;
29+
}
30+
if(now >= count[nx][ny]) {
31+
continue;
32+
}
33+
34+
count[nx][ny] = now;
35+
q.offer(new int[] {nx, ny, now});
36+
}
37+
}
38+
return -1;
39+
}
40+
}

0 commit comments

Comments
 (0)