当前位置:网站首页>leetcode-934:最短的桥
leetcode-934:最短的桥
2022-07-02 23:55:00 【菊头蝙蝠】
题目
在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)
现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。
返回必须翻转的 0 的最小数目。(可以保证答案至少是 1 。)
示例 1:
输入:A = [[0,1],[1,0]]
输出:1
示例 2:
输入:A = [[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:
输入:A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
输出:1
解题
方法一:BFS
1.首先遍历,找到其中岛屿的一个点
2.将第一步中找到的那个岛屿全部标记成-1
3.从第一个岛屿出发,开始BFS,一但遇到1,就说明遇到第二个岛屿了
class Solution {
public:
vector<vector<int>> dirs={
{
-1,0},{
1,0},{
0,1},{
0,-1}};
int shortestBridge(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
//找到其中一个岛屿的点
pair<int,int> startPoint;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==1){
startPoint={
i,j};
goto OUT;
}
}
}
OUT:
//BFS
//将找到的其中一个岛屿全部标记成-1,并把它全部存入q2中
queue<pair<int,int>> q1;//用于bfs
queue<pair<int,int>> q2;//将节点存起来,用于之后的bfs初始值
grid[startPoint.first][startPoint.second]=-1;
q1.push(startPoint);
while(!q1.empty()){
auto [x,y]=q1.front();
q2.push({
x,y});
q1.pop();
for(vector<int>& dir:dirs){
int nx=x+dir[0];
int ny=y+dir[1];
if(nx>=0&&nx<m&&ny>=0&&ny<n&&grid[nx][ny]==1){
q1.push({
nx,ny});
grid[nx][ny]=-1;
}
}
}
//BFS
//-1表示已经访问过的点,0表示还未访问过的点,1表示目的岛屿
//找到值为1的点就说明找到了
int count=0;
while(!q2.empty()){
int l=q2.size();
for(int i=0;i<l;i++){
auto [x,y]=q2.front();
q2.pop();
for(vector<int>& dir:dirs){
int nx=x+dir[0];
int ny=y+dir[1];
if(nx>=0&&nx<m&&ny>=0&&ny<n){
if(grid[nx][ny]==1) return count;
else if(grid[nx][ny]==0){
q2.push({
nx,ny});
grid[nx][ny]=-1;
}
}
}
}
count++;
}
return -1;
}
};
边栏推荐
- Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
- Pageoffice - bug modification journey
- Linux软件:如何安装Redis服务
- Problèmes de configuration lex & yacc & Bison & Flex
- Nc17059 queue Q
- Hundreds of continuous innovation to create free low code office tools
- 【AutoSAR 十二 模式管理】
- An excellent orm in dotnet circle -- FreeSQL
- Vulkan-性能及精细化
- 关于QByteArray存储十六进制 与十六进制互转
猜你喜欢

文件操作IO-Part2

Hdu3507 (slope DP entry)

Solution to the problem of abnormal display of PDF exported Chinese documents of confluence

File operation io-part2

Rust字符串切片、结构体和枚举类

Linux Software: how to install redis service

UART、RS232、RS485、I2C和SPI的介绍

Use Jenkins II job

【AutoSAR 十二 模式管理】

详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
随机推荐
机器学习:numpy版本线性回归预测波士顿房价
NC24840 [USACO 2009 Mar S]Look Up
关于QByteArray存储十六进制 与十六进制互转
mm中的GAN模型架构
【AutoSAR 十一 通信相关机制】
【JetCache】JetCache的配置说明和注解属性说明
form表单实例化
[IELTS reading] Wang Xiwei reading P2 (reading fill in the blank)
[Luogu p4320] road meets (round square tree)
pod生命周期详解
【AutoSAR 七 工具链简介】
Vulkan-性能及精细化
NC50965 Largest Rectangle in a Histogram
Preview word documents online
LeedCode1480. Dynamic sum of one-dimensional array
University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
Nacos+openfeign error reporting solution
FAQ | FAQ for building applications for large screen devices
Multiprocess programming (V): semaphores
node_modules删不掉