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;
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】