317. Shortest Distance from All Buildings

本文介绍了一个算法问题:如何在一个包含建筑和障碍物的网格中找到一块空地来建造一座房子,使得该房子到所有现有建筑物的距离之和最小。文章通过使用广度优先搜索(BFS)策略,对每个建筑物进行遍历并计算距离,最终确定了最佳建造位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 01 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.


对每一个1做bfs,然后更新dist里面的距离。小trick是第一个搜的是0, 第二次搜的是1,不然的话要用visited数组来记录。

bfs里面每一个min刚进去的时候都要更新成最大值。


public class Solution {
    int min = Integer.MAX_VALUE;
    int[] dx = new int[]{1, -1, 0, 0};
    int[] dy = new int[]{0, 0, -1, 1};
	public int shortestDistance(int[][] grid) {
		if(grid == null || grid.length == 0){
			return 0;
		}
        int m = grid.length;
        int n = grid[0].length;

        int[][] dist = new int[m][n];
        int start = 0;
        for(int i=0; i<m; i++){
        	for(int j=0; j<n; j++){
        		if(grid[i][j] == 1){
        			bbb(grid, i, j, dist, start--);
        		}
        	}
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }
	
	
	
	public void bbb(int[][] grid, int m, int n, int[][] dist, int start){
		Queue<int[]> q = new LinkedList<int[]>();
		q.offer(new int[]{m,n});
		int level = 1;
		min = Integer.MAX_VALUE;
		while(!q.isEmpty()){
			int size = q.size();
			for(int i=0; i<size; i++){
				int[] cur = q.poll();
				for(int pos = 0; pos < 4; pos++){
					int x = cur[0] + dx[pos];
					int y = cur[1] + dy[pos];
					if(x>=0 && y>=0 && x<grid.length && y<grid[0].length){
						if(grid[x][y] == start){
							dist[x][y] += level;
							grid[x][y] =  start - 1;
							q.offer(new int[]{x, y});
							min = Math.min(min, dist[x][y]);
						}
					}
				}
			}
			level++;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值