岛屿问题-水源污染-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

相关推荐

11-19 18:44
已编辑
成都理工大学 Java
程序员花海:我面试过100+校招生,大厂后端面试不看ACM,竞赛经历含金量低于你有几份大厂实习 这个简历整体来看不错 可以海投
如何写一份好简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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