题目地址:
https://www.lintcode.com/problem/shortest-distance-from-all-buildings/description
给定一个二维矩阵, 0 0 0代表空地, 1 1 1代表建筑, 2 2 2代表障碍物。要求在一个空地上建一个房子,使得这个房子走到每个建筑的路径长度总和是最小的。路径每次只能向上下左右走一步,不能走到障碍物上,也不能穿过建筑。
思路是BFS。每次遍历的时候,累加一下建筑到每个空地的距离。但需要注意以下几点:
1、遍历的时候,只有
0
0
0才能入队,
1
1
1和
2
2
2都不能入队。遇到
0
0
0的时候累加一下距离和;
2、如果某次从
1
1
1开始BFS的时候,发现某个
0
0
0不可达,那么这个
0
0
0不能成为建房子的候选位置,要做一下标记。
代码如下:
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
/**
* @param grid: the 2D grid
* @return: the shortest distance
*/
public int shortestDistance(int[][] grid) {
// write your code here
int m = grid.length, n = grid[0].length;
// totalDis记录每个空地与所有建筑的距离和
int[][] totalDis = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
// 从(i, j)出发开始累加空地的距离和
bfs(new int[]{i, j}, grid, totalDis);
}
}
}
int res = Integer.MAX_VALUE;
// 枚举每个空地,找到最优空地与所有建筑的距离和
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
res = Math.min(res, totalDis[i][j]);
}
}
}
return res;
}
private void bfs(int[] start, int[][] grid, int[][] totalDis) {
int m = grid.length, n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
queue.offer(start);
boolean[][] visited = new boolean[m][n];
visited[start[0]][start[1]] = true;
int[] d = {1, 0, -1, 0, 1};
int step = 0;
while (!queue.isEmpty()) {
step++;
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
for (int j = 0; j < 4; j++) {
int nextX = cur[0] + d[j], nextY = cur[1] + d[j + 1];
if (inBound(nextX, nextY, grid) && grid[nextX][nextY] != 2 && !visited[nextX][nextY]) {
// 标记为已访问
visited[nextX][nextY] = true;
// 如果是空地,并且之前没有被标记为不可达,则用其更新距离和,并且加入队列
if (grid[nextX][nextY] == 0 && totalDis[nextX][nextY] != Integer.MAX_VALUE) {
totalDis[nextX][nextY] += step;
queue.offer(new int[]{nextX, nextY});
}
}
}
}
}
// 看一下有没有空地是未访问的,如果有,则标记其距离和为无穷大
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!visited[i][j] && grid[i][j] == 0) {
totalDis[i][j] = Integer.MAX_VALUE;
}
}
}
}
private boolean inBound(int x, int y, int[][] grid) {
return 0 <= x && x < grid.length && 0 <= y && y < grid[0].length;
}
}
时间复杂度 O ( r m n ) O(rmn) O(rmn), r r r为建筑物数量,空间 O ( m n ) O(mn) O(mn)。