317. 离建筑物最近的距离

你是个房地产开发商,想要选择一片空地 建一栋大楼。你想把这栋大楼够造在一个距离周边设施都比较方便的地方,通过调研,你希望从它出发能在 最短的距离和 内抵达周边全部的建筑物。请你计算出这个最佳的选址到周边全部建筑物的 最短距离和。

提示:

你只能通过向上、下、左、右四个方向上移动。

给你一个由 0、1 和 2 组成的二维网格,其中:

0 代表你可以自由通过和选择建造的空地
1 代表你无法通行的建筑物
2 代表你无法通行的障碍物

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-from-all-buildings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.LinkedList;
import java.util.Queue;

class Solution {

    private int[][] dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

    public int shortestDistance(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        int[][] distance = new int[n][m];
        int res = Integer.MAX_VALUE;
        int mark = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    res = bfs(grid, n, m, i, j, mark, distance);
                    mark--;
                }
            }
        }

        return res;
    }

    private int bfs(int[][] grid, int n, int m, int i, int j, int mark, int[][] totalDist) {
        int res = Integer.MAX_VALUE;
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{i, j, 0});
        while (!queue.isEmpty()) {
            int[] node = queue.poll();
            for (int[] dir : dirs) {
                int row = node[0] + dir[0];
                int col = node[1] + dir[1];
                if (row >= 0 && row < n && col >= 0 && col < m && grid[row][col] == mark) {
                    int dist = node[2] + 1;
                    totalDist[row][col] += dist;
                    res = Math.min(res, totalDist[row][col]);

                    queue.add(new int[]{row, col, dist});
                    grid[row][col]--;
                }
            }
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }
}
posted @ 2022-01-06 23:07  Tianyiya  阅读(304)  评论(0)    收藏  举报