-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path1293. Shortest Path in a Grid with Obstacles Elimination
42 lines (38 loc) · 1.52 KB
/
1293. Shortest Path in a Grid with Obstacles Elimination
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
34
35
36
37
38
39
40
41
42
class Solution {
public int shortestPath(int[][] grid, int k) {
int m = grid.length, n = grid[0].length;
int[][] DIR = {{0,1}, {1,0}, {0,-1}, {-1,0}};
boolean[][][] v = new boolean[m][n][k+1];
Queue<int[]> q = new LinkedList<>();
int steps = 0;
q.offer(new int[]{0,0,k});
while(!q.isEmpty()) {
int size = q.size();
while(size-- > 0) {
int[] curr = q.poll();
//If curr is the destination; return steps
if(curr[0] == m-1 && curr[1] == n-1) return steps;
//Else go in all valid directions
for(int[] d : DIR) {
int i = curr[0]+d[0];
int j = curr[1]+d[1];
int obs = curr[2];
//Traverse through the valid cells
if(i >= 0 && i < m && j >= 0 && j < n) {
//If cell is empty visit the cell and add in queue
if(grid[i][j] == 0 && !v[i][j][obs]) {
q.offer(new int[]{i,j,obs});
v[i][j][obs] = true;
}
else if(grid[i][j] == 1 && obs > 0 && !v[i][j][obs-1]) {
q.offer(new int[]{i,j,obs-1});
v[i][j][obs-1] = true;
}
}
}
}
++steps;
}
return -1;
}
}