0, 1 or 2, where:- Each
0marks an empty land which you can pass by freely. - Each
1marks a building which you cannot pass through. - Each
2marks an obstacle which you cannot pass through.
Given three buildings at
(0,0), (0,4), (2,2), and an obstacle at (0,2):(1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.Return
7.Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return
-1.Solution
The shortest distance from any empty land to a building can be calculated by BFS starting from the building inO(mn) time. Therefore the we can calculate distance from all buildings to empty lands by t rounds of BFS starting from each building. t is the total number of buildings.In each round, we need maintain two values for every empty land: the distance and the accessibility.
dist[i][j]is the empty land(i, j)to all the buildings.grid[i][j]is reused as the accessibility.
In each round of BFS we can maintain these two values. In the end we just need to find the minimum value of
dist[i][j] where the accessibility equals t.One interesting point is that the
grid[i][j] can also be used to check if (i, j) is visited in this round. At round k (zero based), those has grid[i][j] == k is the empty land unvisited, visited land will have grid[i][j] == k + 1. Here comes the interesting part. One may ask what if grid[i][j] < k? Answer is we do not go into the lands with grid[i][j] < k as if it is an obstacle. Why can we do that? Because grid[i][j] < k
means it is not accessible by at least one of the buildings in previous
rounds. Which means not only this land is not our answer, all the lands
accessible from (i, j) is also not our answer.This might be why it runs faster than many implements. The Java version runs in 13 ms.
Java
1
2
3
4
5
6
7
8
9
10
11
|
class Tuple {
public int y;
public int x;
public int dist;
public Tuple(int y, int x, int dist) {
this.y = y;
this.x = x;
this.dist = dist;
}
}
|
No comments:
Post a Comment