您的位置:首页 > 产品设计 > UI/UE

LeetCode-Shortest Distance from All Buildings

2016-07-21 13:41 465 查看
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:

Each 0 marks an empty land which you can pass by freely.

Each 1 marks a building which you cannot pass through.

Each 2 marks an obstacle which you cannot pass through.

For example, given three buildings at
(0,0)
,
(0,4)
,
(2,2)
, and an obstacle at
(0,2)
:

1 - 0 - 2 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0

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.

Note:

There will be at least one building. If it is not possible to build such house according to the above rules, return -1.

Analysis:

Simply BFS on every building point.

Solution:

public class Solution {
public void addPointToQueue(int[][] grid, int[][] sum, int[][] dis, boolean[][] visited, int curDis,
int nextX, int nextY, Queue<Point> q) {
int row = sum.length;
int col = sum[0].length;
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col || visited[nextX][nextY] || grid[nextX][nextY] > 0) {
return;
}

visited[nextX][nextY] = true;
dis[nextX][nextY] = curDis + 1;
q.add(new Point(nextX, nextY));

sum[nextX][nextY] += curDis + 1;
}

public void BuildingUpdate(int[][] grid, int[][] sum, boolean[][] allReachable, Point start) {
int row = grid.length;
int col = grid[0].length;
int[][] dis = new int[row][col];
boolean[][] visited = new boolean[row][col];

Queue<Point> q = new LinkedList<Point>();
q.add(start);
while (!q.isEmpty()) {
Point cur = q.poll();
int d = dis[cur.x][cur.y];

addPointToQueue(grid, sum, dis, visited, d, cur.x - 1, cur.y, q);
addPointToQueue(grid, sum, dis, visited, d, cur.x + 1, cur.y, q);
addPointToQueue(grid, sum, dis, visited, d, cur.x, cur.y - 1, q);
addPointToQueue(grid, sum, dis, visited, d, cur.x, cur.y + 1, q);
}

// Check reachability
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (!visited[i][j]) {
allReachable[i][j] = false;
}
}

public int shortestDistance(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0)
return -1;

int row = grid.length;
int col = grid[0].length;
int[][] sum = new int[row][col];
boolean[][] allReachable = new boolean[row][col];
for (int i = 0; i < row; i++) {
Arrays.fill(allReachable[i], true);
}

for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (grid[i][j] == 1) {
BuildingUpdate(grid, sum, allReachable, new Point(i, j));
}

int res = Integer.MAX_VALUE;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (allReachable[i][j]) {
res = Math.min(res, sum[i][j]);
}

if (res == Integer.MAX_VALUE)
return -1;
return res;
}
}


Note: the code can be shorter, just I like this which makes the code clear and organized.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: