Skip to content

Commit 66402bc

Browse files
authored
Create 1293. Shortest Path in a Grid with Obstacles Elimination
1 parent 42e1a99 commit 66402bc

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public int shortestPath(int[][] grid, int k) {
3+
4+
int m = grid.length, n = grid[0].length;
5+
int[][] DIR = {{0,1}, {1,0}, {0,-1}, {-1,0}};
6+
boolean[][][] v = new boolean[m][n][k+1];
7+
Queue<int[]> q = new LinkedList<>();
8+
int steps = 0;
9+
q.offer(new int[]{0,0,k});
10+
11+
while(!q.isEmpty()) {
12+
int size = q.size();
13+
14+
while(size-- > 0) {
15+
int[] curr = q.poll();
16+
//If curr is the destination; return steps
17+
if(curr[0] == m-1 && curr[1] == n-1) return steps;
18+
//Else go in all valid directions
19+
for(int[] d : DIR) {
20+
int i = curr[0]+d[0];
21+
int j = curr[1]+d[1];
22+
int obs = curr[2];
23+
24+
//Traverse through the valid cells
25+
if(i >= 0 && i < m && j >= 0 && j < n) {
26+
//If cell is empty visit the cell and add in queue
27+
if(grid[i][j] == 0 && !v[i][j][obs]) {
28+
q.offer(new int[]{i,j,obs});
29+
v[i][j][obs] = true;
30+
}
31+
else if(grid[i][j] == 1 && obs > 0 && !v[i][j][obs-1]) {
32+
q.offer(new int[]{i,j,obs-1});
33+
v[i][j][obs-1] = true;
34+
}
35+
}
36+
}
37+
}
38+
++steps;
39+
}
40+
return -1;
41+
}
42+
}

0 commit comments

Comments
 (0)