317. Shortest Distance from All Buildings

You want to build a house on an empty land that reaches all buildings in the shortest total travel distance.

ๆ‰€ไปฅ่ฆๅพžๆฏๅ€‹ 1 ๅ‡บ็™ผๅŽปๅš bfs, ๅปบๆง‹ๅ‡บๆœ€ๅฐ็š„่ท้›ข๏ผˆreaches all buildings ็š„็ธฝ่ท้›ข๏ผ‰

ๆ‰€ไปฅ้œ€่ฆๅ…ฉๅ€‹่กจ:

dist: ็ธฝ่ท้›ข่กจ

nums: ๅฏไปฅๅˆฐๅนพๅ€‹ๅปบ็ฏ‰็‰ฉ, ๅ› ็‚บๆœ€ๅพŒ่จˆ็ฎ—ๆˆ‘ๅ€‘ๅช่ฆ่ƒฝๅˆฐ reaches all buildings ็š„้ปž,

nums[i][j] ๅฆ‚ๆžœๆ•ธ้‡ = all buildings ๆ•ธ้‡, ๆ‰ๆ˜ฏๅฏไปฅ่“‹ๆˆฟๅญ็š„็ฉบๅœฐ, ๅพž้€™่ฃก้ขๆ‰พ่ท้›ขๆœ€ๅฐ็š„

bfs part:

่ทŸๅพ€ๅธธๅฏซๆณ•ไธ€ๆจฃ, ่ฃก้ขๅ…งๆถตไธ€ๅ€‹ visited[][], ๆฏๆฌก่ท‘bfs้ƒฝๆœƒ้‡็ฝฎ, ๅˆคๆ–ทborder

ๅ…จ้ƒจ่ท‘ๅฎŒๅพŒ, ๆœ€ๅพŒไพ†ๆ‰พๆœ€ๅฐ่ท้›ข (reaches all buildings), ๆ‰พไธๅˆฐๅ›ž -1

time: O(m*n*BFS) = O(m^2*n^2)

space: O(m*n)

class Solution {
    private static final int[][] DIRECTIONS = new int[][]{{1,0}, {0,1}, {-1,0}, {0,-1}};

    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0) return -1;
        int m = grid.length;
        int n = grid[0].length;
        int dist[][] = new int[m][n];
        int nums[][] = new int[m][n];
        
        int buildingNums = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) { // node 1 do BFS
                    buildingNums++;
                    bfs(grid, i, j, dist, nums);
                }
            }
        }
        
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (buildingNums == nums[i][j] && grid[i][j] == 0 && dist[i][j] != 0) {
                    res = Math.min(res, dist[i][j]);
                }
            }
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }
    
    
    private void bfs(int[][] grid, int row, int col, int[][] dist, int[][] nums) {
        int m = grid.length;
        int n = grid[0].length;
        
        boolean visited[][] = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        
        queue.offer(new int[]{row, col});
        visited[row][col] = true;
        
        int distance = 0;
        while (!queue.isEmpty()) {
            distance++;
            int size = queue.size();
            for (int q = 0; q < size; q++) {
                int cell[] = queue.poll();
                for (int dir[] : DIRECTIONS) {
                    int x = cell[0] + dir[0];
                    int y = cell[1] + dir[1];
                    if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y] && grid[x][y] == 0) {
                        visited[x][y] = true;
                        queue.offer(new int[]{x, y});
                        dist[x][y] += distance;
                        nums[x][y]++;
                    }
                }
            }
        }
    }
}

Last updated