-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
47 lines (47 loc) · 1.75 KB
/
Solution.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
class Solution {
public int shortestDistance(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
Deque<int[]> q = new LinkedList<>();
int total = 0;
int[][] cnt = new int[m][n];
int[][] dist = new int[m][n];
int[] dirs = {-1, 0, 1, 0, -1};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
++total;
q.offer(new int[] {i, j});
int d = 0;
boolean[][] vis = new boolean[m][n];
while (!q.isEmpty()) {
++d;
for (int k = q.size(); k > 0; --k) {
int[] p = q.poll();
for (int l = 0; l < 4; ++l) {
int x = p[0] + dirs[l];
int y = p[1] + dirs[l + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0
&& !vis[x][y]) {
++cnt[x][y];
dist[x][y] += d;
q.offer(new int[] {x, y});
vis[x][y] = true;
}
}
}
}
}
}
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0 && cnt[i][j] == total) {
ans = Math.min(ans, dist[i][j]);
}
}
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}