阿里面试真题详解:邮局的建立 II

简介: 阿里面试真题详解:邮局的建立 II

描述
给出一个二维的网格,每一格可以代表墙 2 ,房子 1,以及空 0 (用数字0,1,2来表示),在网格中找到一个位置去建立邮局,使得所有的房子到邮局的距离和是最小的。
返回所有房子到邮局的最小距离和,如果没有地方建立邮局,则返回-1.

  • 你不能穿过房子和墙,只能穿过空地。
  • 你只能在空地建立邮局。

在线评测地址:领扣题库官网

样例1
输入:[[0,1,0,0,0],[1,0,0,2,1],[0,1,0,0,0]]
输出:8
解释: 在(1,1)处建立邮局,所有房子到邮局的距离和是最小的。
样例2
输入:[[0,1,0],[1,0,1],[0,1,0]]
输出:4
解释:在(1,1)处建立邮局,所有房子到邮局的距离和是最小的。

考点:bfs

题解:

  • 本题采用bfs,首次遍历网格,对空地处进行bfs,搜索完成后如果存在房屋没有被vis标记则改空地不可以设置房屋。
  • 朴素的bfs搜索过程中,sun+=dist;实现当前点距离和的更新。
  • now.dis+1每次实现当前两点间距离的更新。
    class Coordinate {
    int x, y;
    public Coordinate(int x, int y) {
    this.x = x;
    this.y = y;
    }
    }

    public class Solution {
    public int EMPTY = 0;
    public int HOUSE = 1;
    public int WALL = 2;
    public int[][] grid;
    public int n, m;
    public int[] deltaX = {0, 1, -1, 0};
    public int[] deltaY = {1, 0, 0, -1};
    
    private List<Coordinate> getCoordinates(int type) {
        List<Coordinate> coordinates = new ArrayList<>();
    
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == type) {
                    coordinates.add(new Coordinate(i, j));
                }
            }
        }
    
        return coordinates;
    }
    
    private void setGrid(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        this.grid = grid;
    }
    
    private boolean inBound(Coordinate coor) {
        if (coor.x < 0 || coor.x >= n) {
            return false;
        }
        if (coor.y < 0 || coor.y >= m) {
            return false;
        }
        return grid[coor.x][coor.y] == EMPTY;
    }
    
    /**
     * @param grid a 2D grid
     * @return an integer
     */
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
    
        // set n, m, grid
        setGrid(grid);
    
        List<Coordinate> houses = getCoordinates(HOUSE);
        int[][] distanceSum = new int[n][m];
        int[][] visitedTimes = new int[n][m];
        for (Coordinate house : houses) {
            bfs(house, distanceSum, visitedTimes);
        }
    
        int shortest = Integer.MAX_VALUE;
        List<Coordinate> empties = getCoordinates(EMPTY);
        for (Coordinate empty : empties) {
            if (visitedTimes[empty.x][empty.y] != houses.size()) {
                continue;
            }
    
            shortest = Math.min(shortest, distanceSum[empty.x][empty.y]);
        }
    
        if (shortest == Integer.MAX_VALUE) {
            return -1;
        }
        return shortest;
    }
    
    private void bfs(Coordinate start,
                     int[][] distanceSum,
                     int[][] visitedTimes) {
        Queue<Coordinate> queue = new LinkedList<>();
        boolean[][] hash = new boolean[n][m];
    
        queue.offer(start);
        hash[start.x][start.y] = true;
    
        int steps = 0;
        while (!queue.isEmpty()) {
            steps++;
            int size = queue.size();
            for (int temp = 0; temp < size; temp++) {
                Coordinate coor = queue.poll();
                for (int i = 0; i < 4; i++) {
                    Coordinate adj = new Coordinate(
                        coor.x + deltaX[i],
                        coor.y + deltaY[i]
                    );
                    if (!inBound(adj)) {
                        continue;
                    }
                    if (hash[adj.x][adj.y]) {
                        continue;
                    }
                    queue.offer(adj);
                    hash[adj.x][adj.y] = true;
                    distanceSum[adj.x][adj.y] += steps;
                    visitedTimes[adj.x][adj.y]++;
                } // direction
            } // for temp
        } // while
    }
    }
    //version 硅谷算法班
    public class Solution {
    /**
     * @param grid: a 2D grid
     * @return: An integer
     */
    public int shortestDistance(int[][] grid) {
        // write your code here
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
    
        int ans = Integer.MAX_VALUE;
    
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 0) {
                    ans = Math.min(ans, bfs(grid, i, j));
                }
            }
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
    
    private int bfs(int[][] grid, int sx, int sy) {
        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();
        boolean[][] v = new boolean[grid.length][grid[0].length];
    
        qx.offer(sx);
        qy.offer(sy);
        v[sx][sy] = true;
    
        int[] dx = {1, -1, 0, 0};
        int[] dy = {0, 0, 1, -1};
    
        int dist = 0;
        int sum = 0;
    
        while (!qx.isEmpty()) {
            dist++;
            int size = qx.size();
            for (int i = 0; i < size; i++) {
                int cx = qx.poll();
                int cy = qy.poll();
                for (int k = 0; k < 4; k++) {
                    int nx = cx + dx[k];
                    int ny = cy + dy[k];
                    if (0 <= nx && nx < grid.length && 0 <= ny && ny < grid[0].length && !v[nx][ny]) {
                        v[nx][ny] = true;
    
                        if (grid[nx][ny] == 1) {
                            sum += dist;
                        }
                        if (grid[nx][ny] == 0) {
                            qx.offer(nx);
                            qy.offer(ny);
                        }
                    }
                }
            }
        }
    
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1 && !v[i][j]) {
                    return Integer.MAX_VALUE;
                }
            }
        }
        return sum;
    }
    }

更多题解参考:九章官网solution

相关文章
|
1月前
|
存储 缓存 Java
什么!?实战项目竟然撞到阿里面试的原题!???关于MyBatis Plus的缓存机制
什么!?实战项目竟然撞到阿里面试的原题!???关于MyBatis Plus的缓存机制
|
1月前
|
存储 算法
【数据结构与算法】【腾讯阿里链表面试题】算法题--链表易懂版讲解
【数据结构与算法】【腾讯阿里链表面试题】算法题--链表易懂版讲解
|
2月前
|
缓存 监控 架构师
阿里面试:Java开发中,应如何避免OOM
在Java开发中,OutOfMemoryError(OOM)错误一直是令开发者头疼的问题,也是Java面试中出现核心频率很高的问题。 那么我们究竟怎么样才能够有效正确的管理内存,日常开发中究竟要注意哪些核心技巧来避免OOM错误。 本文将带大家一起学习10个避免OOM的实用小技巧,让大家在工作中能够有的放矢,避免OOM错误的飞来横祸。
50 1
|
3月前
|
算法 Java 程序员
阿里P8大佬终于把春招面试必备的神级Java面试手册给开源了!
先说说Java Java 作为国人编程开发语言中的 NO.1,已经占比半壁江山,选择入行做 IT 做编程开发的人,基本都把它作为首选语言,进大厂拿高薪也是大多数小伙伴们的梦想。 以前Java 岗位人才的空缺,而需求量又大,所以这种人才供不应求的现状,就是 Java 工程师的薪资待遇相对优厚的原因所在。 但是随着这个从事行业的人数逐渐增多,行业竞争也越来越大,招聘的企业和程序员们都想招聘到自己需要的人才/找到自己理想的岗位,国内大厂尤其是阿里招聘Java岗位居多,导致现在 Java 面试越来越难,内卷早就是大势所趋,万物皆可卷,卷的我们都见怪不怪了。 那么,阿里Java面试难度大吗?
|
3月前
|
NoSQL Java 关系型数据库
阿里技术三面:P7想靠资历打败我,却惨败于这800页面试热题下
阿里巴巴,这个中国互联网行业中能排上前三的企业,面试是非常讲究的。通常都是三面技术面+HR面,可是多少心怀阿里梦的工作者惨败三面之中,连HR面都没见着就败了。那如何通过技术三面呢?我来介绍介绍(这里是指我技术三面的经验)
|
3月前
|
算法 Java 关系型数据库
在家“闭关”,阿里竟发来视频面试,4面顺利拿下offer
关于个人呢,我是一个普通的双非本科生,在校成绩不错,各方面的表现自我感觉也比较突出,今年大四即将毕业,对自己进入大厂工作是很有信心的,我的方向是Java,也知道现在Java的竞争比较激烈,大厂比较难进,但我丝毫不胆怯。当然,我还是很走“狗屎运”的,没想到闭关在家期间,也能收到阿里发来的视频面,还一路顺利拿下了offer。
|
3月前
|
安全 Java 数据库连接
啃完这些Spring知识点,我竟吊打了阿里面试官(附面经+笔记)
对于开发同学来说,Spring 框架熟悉又陌生。 熟悉:开发过程中无时无刻不在使用 Spring 的知识点;陌生:对于基本理论知识疏于整理与记忆。导致很多同学面试时对于 Spring 相关的题目知其答案,但表达不够完整准确。
|
27天前
|
Java 程序员
java线程池讲解面试
java线程池讲解面试
50 1
|
2月前
|
存储 关系型数据库 MySQL
2024年Java秋招面试必看的 | MySQL调优面试题
随着系统用户量的不断增加,MySQL 索引的重要性不言而喻,对于后端工程师,只有在了解索引及其优化的规则,并应用于实际工作中后,才能不断的提升系统性能,开发出高性能、高并发和高可用的系统。 今天小编首先会跟大家分享一下MySQL 索引中的各种概念,然后介绍优化索引的若干条规则,最后利用这些规则,针对面试中常考的知识点,做详细的实例分析。
248 0
2024年Java秋招面试必看的 | MySQL调优面试题
|
2月前
|
存储 算法 Java
铁子,你还记得这些吗----Java基础【拓展面试常问题型】
铁子,你还记得这些吗----Java基础【拓展面试常问题型】
46 1