forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_317.java
67 lines (61 loc) · 2.69 KB
/
_317.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
package com.fishercoder.solutions;
import java.util.LinkedList;
import java.util.Queue;
public class _317 {
public static class Solution1 {
public int shortestDistance(int[][] grid) {
int m = grid.length;
if (m == 0) {
return -1;
}
int n = grid[0].length;
int[][] reach = new int[m][n];
int[][] distance = new int[m][n];
int[] shift = new int[]{0, 1, 0, -1,
0};//how these five elements is ordered is important since it denotes the neighbor of the current node
int numBuilding = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
numBuilding++;
int dist = 1;
boolean[][] visited = new boolean[m][n];
Queue<int[]> q = new LinkedList<int[]>();
q.offer(new int[]{i, j});
while (!q.isEmpty()) {
int size = q.size();
for (int l = 0; l < size; l++) {
int[] current = q.poll();
for (int k = 0; k < 4; k++) {
int nextRow = current[0] + shift[k];
int nextCol = current[1] + shift[k + 1];
if (nextRow >= 0
&& nextRow < m
&& nextCol >= 0
&& nextCol < n
&& !visited[nextRow][nextCol]
&& grid[nextRow][nextCol] == 0) {
distance[nextRow][nextCol] += dist;
visited[nextRow][nextCol] = true;
reach[nextRow][nextCol]++;
q.offer(new int[]{nextRow, nextCol});
}
}
}
dist++;
}
}
}
}
int result = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0 && reach[i][j] == numBuilding && distance[i][j] < result) {
result = distance[i][j];
}
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}
}