3
3
import java .util .LinkedList ;
4
4
import java .util .Queue ;
5
5
6
- /**
7
- * 317. Shortest Distance from All Buildings
8
- *
9
- * You want to build a house on an empty land which reaches all buildings in the shortest amount of distance.
10
- * You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
11
-
12
- Each 0 marks an empty land which you can pass by freely.
13
- Each 1 marks a building which you cannot pass through.
14
- Each 2 marks an obstacle which you cannot pass through.
15
-
16
- For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
17
-
18
- 1 - 0 - 2 - 0 - 1
19
- | | | | |
20
- 0 - 0 - 0 - 0 - 0
21
- | | | | |
22
- 0 - 0 - 1 - 0 - 0
23
-
24
- The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
25
-
26
- Note:
27
- There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
28
- */
29
-
30
6
public class _317 {
31
7
public static class Solution1 {
32
8
public int shortestDistance (int [][] grid ) {
@@ -37,8 +13,8 @@ public int shortestDistance(int[][] grid) {
37
13
int n = grid [0 ].length ;
38
14
int [][] reach = new int [m ][n ];
39
15
int [][] distance = new int [m ][n ];
40
- int [] shift = new int [] {0 , 1 , 0 , -1 ,
41
- 0 };//how these five elements is ordered is important since it denotes the neighbor of the current node
16
+ int [] shift = new int []{0 , 1 , 0 , -1 ,
17
+ 0 };//how these five elements is ordered is important since it denotes the neighbor of the current node
42
18
int numBuilding = 0 ;
43
19
44
20
for (int i = 0 ; i < m ; i ++) {
@@ -49,7 +25,7 @@ public int shortestDistance(int[][] grid) {
49
25
boolean [][] visited = new boolean [m ][n ];
50
26
51
27
Queue <int []> q = new LinkedList <int []>();
52
- q .offer (new int [] {i , j });
28
+ q .offer (new int []{i , j });
53
29
while (!q .isEmpty ()) {
54
30
int size = q .size ();
55
31
for (int l = 0 ; l < size ; l ++) {
@@ -58,15 +34,15 @@ public int shortestDistance(int[][] grid) {
58
34
int nextRow = current [0 ] + shift [k ];
59
35
int nextCol = current [1 ] + shift [k + 1 ];
60
36
if (nextRow >= 0
61
- && nextRow < m
62
- && nextCol >= 0
63
- && nextCol < n
64
- && !visited [nextRow ][nextCol ]
65
- && grid [nextRow ][nextCol ] == 0 ) {
37
+ && nextRow < m
38
+ && nextCol >= 0
39
+ && nextCol < n
40
+ && !visited [nextRow ][nextCol ]
41
+ && grid [nextRow ][nextCol ] == 0 ) {
66
42
distance [nextRow ][nextCol ] += dist ;
67
43
visited [nextRow ][nextCol ] = true ;
68
44
reach [nextRow ][nextCol ]++;
69
- q .offer (new int [] {nextRow , nextCol });
45
+ q .offer (new int []{nextRow , nextCol });
70
46
}
71
47
}
72
48
}
0 commit comments