Skip to content

Commit 100ec91

Browse files
author
hieu
committed
Solve Problem 1293 - Shortest Path In Grid With Obstacles Elimination
1 parent bd61330 commit 100ec91

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
### Trie:
1313
### Binary Search: [#](https://leetcode.com/discuss/interview-question/313216/)
1414
### Minimax: 913
15-
### Matrix: 1368, 1292, 864
15+
### Matrix: 1368, 1292, 864, 1293
1616

1717
# Favorite:
1818

src/contest/ReadMe.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ public class ReadMe {
66

77
// tree: 1339[v] 1325[v] 1379[v] 1372[v]
88
// graph: 997[v] 1361[v] 1043[v] 1387[~]
9-
// dfs: 1319[v] 1254[v] 1377[v] 1145
10-
// bfs: 1345[v] 1368[!] 1311[v] 1293
9+
// dfs: 1319[v] 1254[v] 1377[v] 1145[x]
10+
// bfs: 1345[v] 1368[!] 1311[v] 1293[x]
1111
// backtrack: 1307[!] 1239[v] 1219[v] 1291
1212
// dp: 1349[!] 1340[v] 1367[v] 1388
1313
// divide & conquer: 932[!] 514 903[v] 327
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package graph.bfs;
2+
3+
import java.util.Arrays;
4+
import java.util.LinkedList;
5+
import java.util.Queue;
6+
7+
public class Problem1293_ShortestPathInGridWithObstaclesElimination {
8+
9+
public int shortestPath(int[][] A, int K) {
10+
int m = A.length, n = A[0].length;
11+
if (m == 1 && n == 1) return A[0][0];
12+
if (K > m-1+n-1) return m+n-2;
13+
14+
int dirs[][] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
15+
int breaks[][] = new int[m][n];
16+
for (int[] row: breaks) Arrays.fill(row, m+n-2);
17+
breaks[0][0] = A[0][0];
18+
19+
Queue<int[]> queue = new LinkedList<>();
20+
queue.offer(new int[] {0, 0});
21+
22+
int res = 0;
23+
while (!queue.isEmpty()) {
24+
int size = queue.size();
25+
while (size-- > 0) {
26+
int e[] = queue.poll(), i = e[0], j = e[1];
27+
for (int[] d : dirs) {
28+
int x = i+d[0], y = j+d[1];
29+
if (x < 0 || x >= m || y < 0 || y >= n) continue;
30+
int b = breaks[i][j] + A[x][y];
31+
if (b > K || b >= breaks[x][y]) continue;
32+
if (x == m-1 && y == n-1) return res+1;
33+
queue.offer(new int[] {x, y});
34+
breaks[x][y] = b;
35+
}
36+
}
37+
res++;
38+
}
39+
40+
return -1;
41+
}
42+
}

0 commit comments

Comments
 (0)