1、题目描述
2、解题思路
本题需要对每一个建筑物分别进行一次 BFS。
BFS 的作用是计算每一个空格到这个建筑物的距离。
定义一个数组 totalDist[][],其中 totalDist[i][j] 表示坐标 (i,j) 的空格到达所有建筑物的距离之和。
因此,每一次 BFS,都是对 totalDist[][] 进行累加的过程。
这里还需要注意一点的是:建筑物个数为 n,因此每一个空格都会被遍历 n,次,因为要计算空格到达每一个建筑物的距离嘛。
因此,我们需要定义一个变量 mark = 0,初始时,空格是用 mark 表示,当我计算完一个建筑物时,mark–,所有的空格变成用 -1 表示了。
这样做就是为了解决“BFS时空格不能重复遍历,但是遍历建筑物时,空格又要重复使用”的矛盾。
3、解题代码
class Solution {
private final int[][] directions = {
{
0, -1}, {
0, 1}, {
-1, 0}, {
1, 0}};
// 思路:
// (1) 从每一个建筑物开始进行广度优先搜索
// (2) 在搜索的同时计算每一个空格到这个建筑物的距离
// (3) 在搜索的同时将每一个空格到每一个建筑物的距离进行累加,得到每个空格到所有建筑物的距离
// (4) 取空格到所有建筑物的最小距离
public int shortestDistance(int[][] grid) {
int rows = grid.length;
if (rows == 0) {
return 0;
}
int cols = grid[0].length;
int[][] totalDist = new int[rows][cols];
int ans = Integer.MAX_VALUE;
// 用于标记空地
int mark = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// (1) 从每一个建筑物开始进行广度优先搜索
if (grid[i][j] == 1) {
ans = bfs(grid, rows, cols, i, j, mark, totalDist);
// 每次遍历搜索完一个建筑物,这个标记减一,表示所有空地被遍历一次了
mark--;
}
}
}
return ans;
}
private int bfs(int[][] grid, int rows, int cols, int x, int y, int mark, int[][] totalDist) {
int ans = Integer.MAX_VALUE;
Queue<int[]> queue = new LinkedList<>();
// 队列中每个数组有 3 个元素,分别表示:
// 第一个元素和第二个元素表示坐标值
// 第三个元素表示当前坐标到建筑物的距离
// 第三个元素的初始值为 0 的原因是:一开始的时候从当前建筑物到当前建筑物的距离是 0
queue.add(new int[]{
x, y, 0});
while (!queue.isEmpty()) {
int[] curPoint = queue.poll();
int currDist = curPoint[2];
for (int[] direction : directions) {
int newX = curPoint[0] + direction[0];
int newY = curPoint[1] + direction[1];
if (newX >= 0 && newX < rows && newY >= 0 && newY < cols && // 不超出边界
grid[newX][newY] == mark) {
// 当前点是空地
// (2) 在搜索的同时计算每一个空格到这个建筑物的距离
int dist = currDist + 1;
// (3) 在搜索的同时将每一个空格到每一个建筑物的距离进行累加
totalDist[newX][newY] += dist;
// (4) 取空格到所有建筑物的最小距离
ans = Math.min(ans, totalDist[newX][newY]);
queue.add(new int[]{
newX, newY, dist});
// 当前点处理过了
grid[newX][newY]--;
}
}
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}