0-1BFS
# 2290. 到达角落需要移除障碍物的最小数目 (opens new window)
class Solution {
int[][] dirs = new int[][]{{-1,0},{1,0},{0,1},{0,-1}};
public int minimumObstacles(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dis = new int[m][n];
for(int[] row:dis)
Arrays.fill(row,Integer.MAX_VALUE);
dis[0][0] = 0;
LinkedList<int[]> que = new LinkedList<>();
que.offer(new int[]{0,0});
while(!que.isEmpty()){
int[] cur = que.poll();
int x = cur[0];
int y = cur[1];
for(int[] dir:dirs){
int nx = x+dir[0];
int ny = y+dir[1];
if(nx>=0&&nx<m && ny>=0&&ny<n){
int val = grid[nx][ny];
if(dis[x][y]+val<dis[nx][ny]){
dis[nx][ny] = dis[x][y]+val;
if(val==0)
que.offerFirst(new int[]{nx,ny});
else
que.offerLast(new int[]{nx,ny});
}
}
}
}
return dis[m-1][n-1];
}
}
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
33
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
33