-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_1293_ShortestPathInGrid.java
More file actions
58 lines (40 loc) · 1.4 KB
/
_1293_ShortestPathInGrid.java
File metadata and controls
58 lines (40 loc) · 1.4 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.LinkedList;
import java.util.Queue;
public class _1293_ShortestPathInGrid {
public static int shortestPath(int[][] grid,int k){
int m = grid.length;
int n = grid[0].length;
Queue<int[]> q = new LinkedList<>();
boolean[][][] visited = new boolean[m][n][k+1];
q.offer(new int[]{0,0,k,0});
int[][] dir = {{1,0},{-1,0},{0,1},{0,-1}};
// left,right,bottom, up
while (!q.isEmpty()) {
int[] curr = q.poll();
int r = curr[0];
int c = curr[1];
int rem = curr[2];
int step = curr[3];
if (r == m-1 && c == n-1) {
return step;
}
for (int[] d : dir) {
int nr = r + d[0];
int nc = c + d[1];
if (nr >= 0 && nc >= 0 && nr < m && nc < n) {
int newRem = rem - grid[nr][nc];
if (newRem >= 0 && !visited[nr][nc][newRem]) {
visited[nr][nc][newRem] = true;
q.offer(new int[]{nr,nc,newRem,step+1});
}
}
}
}
return -1;
}
public static void main(String[] args){
int[][] grid = {{0,0,0},{1,1,0},{0,0,0},{0,1,1},{0,0,0}};
int step = shortestPath(grid, 1);
System.out.println("Step = "+ step);
}
}