资讯专栏INFORMATION COLUMN

Shortest Distance from All Buildings

DC_er / 2979人阅读

摘要:如果该没有被之前所有的访问过,就不可能成为答案根据要求的位置能到所有的,其他与它相邻的点也是这样。和用矩阵比,缩小了每次遍历的范围。

Shortest Distance from All Buildings

题目链接:https://leetcode.com/problems...

这道题要求最短的距离,一般这种要求可以到的地方的距离,都需要把整个图遍历一遍,遍历一般就是bfs和dfs。这道题不用dfs的原因是:empty的位置到building的距离是按最小值来算的,用dfs每次如果放入depth不一定是最小的距离,每次都得更新,没有效率。这道题用bfs的原因:一样的原因,因为距离就是按照最小的距离来算的,完全是bfs的思路。
visited一般两种方式:用一个boolean的矩阵,直接改写grid的值。这里用第二种。-grid[i] [j]表示(i, j)点可以reach到的building数目。当grid[i] [j] == # of buildings so far时,证明当前点还没被visited,且当前点被之前所有的buildings都visited过,那么每次bfs只访问这些点。如果该point没有被之前所有的buildings访问过,就不可能成为答案(根据要求empty的位置能到所有的buildings),其他与它相邻的点也是这样。和用boolean矩阵比,缩小了每次遍历的范围。
从每一个building,即grid[i] [j] == 1的点开始做bfs层次遍历。

用一个distance矩阵来记录(i, j)到所有building的距离和,对每一个building做bfs

每次bfs的时候,更新distance[i] [j]的值:

Queue 记录point

更新level += 1

go over当前level的全部point

if (i, j)在图内&grid[i] [j] = -num:

distance[i] [j] += level

grid[i] [j] --

q.offer(i, j)

go over整个distance数组,当-grid[i] [j] == # of buildings时,更新最小的距离值

public class Solution {
    public int shortestDistance(int[][] grid) {
        /* approach: bfs, distance array
         * for each building, do a bfs, add the distance
         * variable: num: record number of buildings already searched
         * visited => use the grid => do -- if visited[i][j] = -num
         * result: the grid[i][j] == -(number of buildings) is the possible
         *         find the smallest distance[i][j]
         */
         distance = new int[grid.length][grid[0].length];
         int num = 0;
         for(int i = 0; i < grid.length; i++) {
             for(int j = 0; j < grid[0].length; j++) {
                 if(grid[i][j] == 1) {
                     bfs(grid, i, j, -num);
                     num++;
                 }
             }
         }
         int result = Integer.MAX_VALUE;
         // find the smallest distance
         for(int i = 0; i < grid.length; i++) {
             for(int j = 0; j < grid[0].length; j++) {
                 if(grid[i][j] == -num) result = Math.min(result, distance[i][j]);
             }
         }
         return result == Integer.MAX_VALUE ? -1 : result;
    }
    
    int[][] distance;
    int[] dx = new int[] {-1, 1, 0, 0};
    int[] dy = new int[] {0, 0, -1, 1};
    private void bfs(int[][] grid, int x, int y, int num) {
        Queue q = new LinkedList();
        q.offer(new int[] {x, y});
        int len = 0;
        while(!q.isEmpty()) {
            len++;
            // current level
            for(int j = q.size(); j > 0; j--) {
                int[] cur = q.poll();
                // 4 directions
                for(int i = 0; i < 4; i++) {
                    int nx = cur[0] + dx[i], ny = cur[1] + dy[i];
                    if(nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == num) {
                        distance[nx][ny] += len;
                        q.offer(new int[] {nx, ny});
                        grid[nx][ny]--;
                    }
                }
            }
        }
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66556.html

相关文章

  • [LeetCode] 317. Shortest Distance from All Buildin

    Problem 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 0, 1 or...

    wall2flower 评论0 收藏0
  • leetcode 317 shortest distance from all buildings

    摘要:从第一个点出发表示空地,表示已经走过的空地,避免重复。看起来就像一层层的涂色。 1 0 2 0 1 0 0 0 0 0 0 0 1 0 0 第一个building, 把涂色把0变成-1, 同一层最终会涂成相同颜色-1 1 -1 2 -1 1 -1 -1 -1 -1 -1 -1 ...

    yanbingyun1990 评论0 收藏0
  • LeetCode[218] The Skyline Problem

    摘要:复杂度思路利用的思想,先分成左右两部分,再进行。每次都要将的左上角和右下角推进,进行计算。观察左边和右边进行。 LeetCode[218] The Skyline Problem A citys skyline is the outer contour of the silhouette formed by all the buildings in that city when vie...

    keithyau 评论0 收藏0
  • Walls and Gates

    摘要:题目链接这道题感觉是那道的简化版,思路都是一样的。是把所有的点都先放到里面,然后一起遍历。这种写法的好处是保证了每个点都只被放进一次,不会重复遍历。保证了时间复杂是。可以不写成层次遍历的形式,直接,的程序 Walls and Gates 题目链接:https://leetcode.com/problems... 这道题感觉是那道Shortest Distance from All Bu...

    CKJOKER 评论0 收藏0
  • [LeetCode] 126. Word Ladder II

    摘要:存放过程中的所有集合为所有的结尾,则顺序存放这个结尾对应的中的所有存放同一个循环的新加入的,在下一个循环再依次对其中元素进行进一步的把首个字符串放入新,再将放入,并将键值对放入,进行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...

    wayneli 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<