-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind the Safest Path in a Grid.java
69 lines (57 loc) · 2.11 KB
/
Find the Safest Path in a Grid.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
class Solution {
private int[] roww = {0, 0, -1, 1};
private int[] coll = {-1, 1, 0, 0};
private void bfs(List<List<Integer>> grid, int[][] score, int n) {
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid.get(i).get(j) == 1) {
score[i][j] = 0;
q.offer(new int[]{i, j});
}
}
}
while (!q.isEmpty()) {
int[] t = q.poll();
int x = t[0], y = t[1];
int s = score[x][y];
for (int i = 0; i < 4; i++) {
int newX = x + roww[i];
int newY = y + coll[i];
if (newX >= 0 && newX < n && newY >= 0 && newY < n && score[newX][newY] > 1 + s) {
score[newX][newY] = 1 + s;
q.offer(new int[]{newX, newY});
}
}
}
}
public int maximumSafenessFactor(List<List<Integer>> grid) {
int n = grid.size();
if (grid.get(0).get(0) == 1 || grid.get(n - 1).get(n - 1) == 1) {
return 0;
}
int[][] score = new int[n][n];
for (int[] row : score) Arrays.fill(row, Integer.MAX_VALUE);
bfs(grid, score, n);
boolean[][] vis = new boolean[n][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
pq.offer(new int[]{score[0][0], 0, 0});
while (!pq.isEmpty()) {
int[] temp = pq.poll();
int safe = temp[0];
int i = temp[1], j = temp[2];
if (i == n - 1 && j == n - 1) return safe;
vis[i][j] = true;
for (int k = 0; k < 4; k++) {
int newX = i + roww[k];
int newY = j + coll[k];
if (newX >= 0 && newX < n && newY >= 0 && newY < n && !vis[newX][newY]) {
int s = Math.min(safe, score[newX][newY]);
pq.offer(new int[]{s, newX, newY});
vis[newX][newY] = true;
}
}
}
return -1;
}
}