-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1293.shortest-path-in-a-grid-with-obstacles-elimination.java
112 lines (110 loc) · 2.9 KB
/
1293.shortest-path-in-a-grid-with-obstacles-elimination.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* @lc app=leetcode id=1293 lang=java
*
* [1293] Shortest Path in a Grid with Obstacles Elimination
*
* https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/description/
*
* algorithms
* Hard (42.47%)
* Likes: 510
* Dislikes: 8
* Total Accepted: 16.7K
* Total Submissions: 39K
* Testcase Example: '[[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]]\n1'
*
* Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In
* one step, you can move up, down, left or right from and to an empty cell.
*
* Return the minimum number of steps to walk from the upper left corner (0, 0)
* to the lower right corner (m-1, n-1) given that you can eliminate at most k
* obstacles. If it is not possible to find such walk return -1.
*
*
* Example 1:
*
*
* Input:
* grid =
* [[0,0,0],
* [1,1,0],
* [0,0,0],
* [0,1,1],
* [0,0,0]],
* k = 1
* Output: 6
* Explanation:
* The shortest path without eliminating any obstacle is 10.
* The shortest path with one obstacle elimination at position (3,2) is 6. Such
* path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
*
*
*
*
* Example 2:
*
*
* Input:
* grid =
* [[0,1,1],
* [1,1,1],
* [1,0,0]],
* k = 1
* Output: -1
* Explanation:
* We need to eliminate at least two obstacles to find such a walk.
*
*
*
* Constraints:
*
*
* grid.length == m
* grid[0].length == n
* 1 <= m, n <= 40
* 1 <= k <= m*n
* grid[i][j] == 0 or 1
* grid[0][0] == grid[m-1][n-1] == 0
*
*
*/
// @lc code=start
class Solution {
int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
public int shortestPath(int[][] grid, int k) {
int n = grid.length;
int m = grid[0].length;
Queue<int[]> q = new LinkedList();
boolean[][][] visited = new boolean[n][m][k+1];
visited[0][0][0] = true;
q.offer(new int[]{0,0,0});
int res = 0;
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i<size; i++){
int[] info = q.poll();
int r = info[0], c = info[1], curK = info[2];
if(r==n-1 && c==m-1){
return res;
}
for(int[] dir : dirs){
int nextR = dir[0] + r;
int nextC = dir[1] + c;
int nextK = curK;
if(nextR>=0 && nextR<n && nextC>=0 && nextC<m){
if(grid[nextR][nextC]==1){
nextK++;
}
if(nextK<=k && !visited[nextR][nextC][nextK]){
visited[nextR][nextC][nextK] = true;
q.offer(new int[]{nextR, nextC, nextK});
}
}
}
}
res++;
}
return -1;
}
}
// @lc code=end