934. 最短的桥

在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)

现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。

返回必须翻转的 0 的最小数目。(可以保证答案至少是 1 。)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-bridge
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.LinkedList;
import java.util.Queue;

class Solution {

    private int[][] grid;

    private Queue<int[]> queue = new LinkedList<>();

    private int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    private void fillQueue(int x, int y) {
        grid[x][y] = 2;
        queue.offer(new int[]{x, y, 0});
        for (int i = 0; i < directions.length; ++i) {
            int nx = x + directions[i][0];
            int ny = y + directions[i][1];
            if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1) {
                fillQueue(nx, ny);
            }
        }
    }

    public int shortestBridge(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }

        this.grid = grid;

        boolean first = true;

        for (int i = 0; i < grid.length && first; ++i) {
            for (int j = 0; j < grid[0].length && first; ++j) {
                if (grid[i][j] == 1) {
                    fillQueue(i, j);
                    first = false;
                }
            }
        }

        while (!queue.isEmpty()) {
            int[] point = queue.poll();
            for (int i = 0; i < directions.length; ++i) {
                int nx = point[0] + directions[i][0];
                int ny = point[1] + directions[i][1];
                if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length) {
                    if (grid[nx][ny] == 1) {
                        return point[2];
                    }
                    if (grid[nx][ny] == 0) {
                        queue.offer(new int[]{nx, ny, point[2] + 1});
                        grid[nx][ny] = 3;
                    }
                }
            }
        }

        return 0;
    }
}
posted @   Tianyiya  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示