01表示岛屿和水的模型中,求与给定点最近的岛屿的距离


public int minDistanceToIsland(int[][] grid, int rowIndex, int colIndex) {
        if (grid.length == 0) return -1;

        int m = grid.length;
        int n = grid[0].length;
        int distance = 0;

        int[][] next = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{rowIndex, colIndex});
        grid[rowIndex][colIndex] = 2;

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                int[] curr = queue.poll();
                for (int j = 0; j < next.length; j++) {
                    int nextR = curr[0] + next[j][0];
                    int nextC = curr[1] + next[j][1];

                    if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n || grid[nextR][nextC] == 2) continue;
                    if (grid[nextR][nextC] == 1) return distance + 1;
                    queue.offer(new int[]{nextR, nextC});
                    grid[nextR][nextC] = 2;
                }
            }
            distance++;
        }

        return -1;
    }
public int minDistanceToIsland(int[][] grid, int i, int j) {

        int m = grid.length;
        if (m == 0) return 0;
        int n = grid[0].length;

        if (i < 0 || i >= m || j < 0 || j >= n) return 0;

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{i, j});

        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int depth = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int k = 0; k < size; k++) {
                int[] cell = queue.poll();
                if (grid[cell[0]][cell[1]] == 1) return depth;
                grid[cell[0]][cell[1]] = 2;
                for (int[] d : dirs) {
                    int r = cell[0] + d[0];
                    int c = cell[1] + d[1];

                    if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 2)
                        continue;
                    queue.offer(new int[]{r, c});
                }
            }
            depth++;
        }
        return depth;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值