[Leetcode] 317. Shortest Distance from All Buildings

该题目是LeetCode中的317题,是对原有问题的扩展,增加了两个条件:1. 点自身不能作为聚集点;2. 数字2表示障碍物。由于这些限制,原有的最优解决方案不再适用。当前已知的最佳解法是使用广度优先搜索(BFS)。从每个建筑物开始向外BFS,累加计算可达点的距离。如果存在无法到达的建筑物,则后续会忽略这些点,作为剪枝处理。最终遍历所有计算过的点,寻找最小的累加值,若存在则返回。这是相对简单的BFS问题。以下是解题代码。

这题算是https://blog.youkuaiyun.com/chaochen1407/article/details/82720327 的延伸。相当于那一题加了两个限定条件:1. 1本身不能成为聚集点。2.多了2这个数字代表obstacle。

加了这两个限定条件,就没办法采取那道题目的最优解决法了。目前所知的最优解就是遍历bfs。就是以每个building为起始点,然后往外bfs,对每个能达到的点进行叠加计算。如果存在某个点有building无法到达,那么以后这个点都会被忽略,可以认为这是一种截枝处理。最后遍历计算过的点,从中找到最小的叠加值(如果存在的话)。并不是很难的bfs。下面给出代码:

    public static int[][] DIR = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public int shortestDistance(int[][] grid) {
        int[][] total = new int[grid.length][grid[0].length];
        int[][] marker = new int[grid.length][grid[0].length];
        int buildCnt = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    Queue<int[]> bfsQ = new LinkedList<int[]>();
                    for (int[] dir : DIR) {
                        bfsQ.add(new int[]{i + dir[0], j + dir[1], 1});
                    }
                    buildCnt++;
                    while (!bfsQ.isEmpty()) {
                        int[] curPt = bfsQ.poll();
                        int x = curPt[0];
                        int y = curPt[1];
                        if (x >= 0
                           && x < grid.length
                           && y >= 0
                           && y < grid[0].length
                           && grid[x][y] == 0
                           && marker[x][y] == buildCnt - 1) {
                            marker[x][y] = buildCnt;
                            total[x][y] += curPt[2];
                            for (int[] dir : DIR) {
                                bfsQ.add(new int[]{x + dir[0], y + dir[1], curPt[2] + 1});
                            }
                        }
                    }
                }
            }
        }
        
        boolean found = false;
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < total.length; i++) {
            for (int j = 0; j < total[0].length; j++) {
                if (marker[i][j] == buildCnt) {
                    found = true;
                    result = Math.min(result, total[i][j]);
                }
            }
        }
        
        return found ? result : -1;
    }

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值