岛屿问题-水源污染-bfs

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String[] lines = scanner.nextLine().split(",");
        int n = (int) Math.sqrt(lines.length);

        int[][] map = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                map[i][j] = Integer.parseInt(lines[i * n + j]);
            }
        }
        System.out.println(maxDistance(map));
    }

    public static int maxDistance(int[][] grid) {
        int n = grid.length;
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        Queue<int[]> queue = new ArrayDeque<>();
        Set<int[]> visited = new HashSet<>();

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid.length; j++) {
                if (grid[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        boolean hasZero = false;
        int[] current = null;
        while (!queue.isEmpty()) {
            current = queue.poll();
            int x = current[0];
            int y = current[1];

            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx < 0 || ny < 0 || nx >= n || ny >= n || grid[nx][ny] != 0) {
                    continue;
                }
                hasZero = true;
                grid[nx][ny] = grid[x][y] + 1;
                queue.offer(new int[]{nx, ny});
            }
        }
        if (!hasZero || current == null) {
            return -1;
        }
        return grid[current[0]][current[1]] - 1;


    }

全部评论
你这个原题是牛客上的?在哪可以访问到原题
点赞 回复 分享
发布于 2022-08-05 10:53

相关推荐

03-04 15:02
已编辑
南京大学 Java
3.3&nbsp;一面岗位:&nbsp;后台开发部门:&nbsp;腾讯云场景题偏多,没问项目,没手撕,时长半小时1.&nbsp;自我介绍2.&nbsp;Java基础:-&nbsp;Treemap&nbsp;&amp;&nbsp;HashMap区别-&nbsp;ArrayList,&nbsp;添加n个数(n较大),会发生什么(应该是想问ArrayList的扩容机制)-&nbsp;考虑扩容的情况下这个过程的复杂度多少(说明复杂度计算思路即可,不需要给出具体的复杂度)3.&nbsp;并发:-&nbsp;项目里怎么用多线程的(一开始答了具体场景,不过面试官想听的是线程池,Synchronized这些...)-&nbsp;volatile&nbsp;&amp;&nbsp;synchronized-&nbsp;这里还问了一个,不过忘了...-&nbsp;假设项目里用了很多synchronized拖慢了系统效率,让你重构项目,你怎么设计?&nbsp;(真不会,回了一个参考乐观锁的设计用版本号之类的,然后这个话题就过了)4.&nbsp;JVM-&nbsp;JVM垃圾回收,怎么判断对象有没有被引用?&nbsp;(可达性分析)-&nbsp;GC&nbsp;Root有哪些-&nbsp;遇到OOM怎么排查5.&nbsp;场景-&nbsp;设计一个数据结构,用于在搜索框中搜索人名(不知道是不是这个意思,答了字典树这个结构)-&nbsp;使用字典树存储的话空间复杂度是多少(同前面,给出计算思路就行,不需要具体的值)-&nbsp;问了下简历上项目的背景,项目的具体内容没问-&nbsp;项目里的难点/印象深刻的点,咋解决的-&nbsp;针对上一点提了一个发散性的场景题(让你设计个xxx,你的思路)然后反问,无手撕。---春招第一面,被场景设计问题拷打麻了,就当练习了,不敢奢望能过,后续随缘了3.4更新,已挂
_追梦旅人_:大家考虑深圳睿联不,我们正在春招,可在我主页看岗位,感兴趣可直接投递~
查看15道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务