当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

pod生命周期详解

Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud

使用jenkins之二Job

百度智能云牵头打造智能云综合标准化平台

如何系统学习机器学习

MySQL 23 classic interview hanging interviewer

Rust string slicing, structs, and enumeration classes

文件操作IO-Part2

Two common methods and steps of character device registration

ftrace工具的介绍及使用
随机推荐
Preview word documents online
How to find out the currently running version of Solr- How do I find out version of currently running Solr?
UART、RS232、RS485、I2C和SPI的介绍
lex && yacc && bison && flex 配置的问题
NC50965 Largest Rectangle in a Histogram
logback配置文件
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
Nc20806 District interval
NC17059 队列Q
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
腾讯云免费SSL证书扩展文件含义
There is an unknown problem in inserting data into the database
百度智能云牵头打造智能云综合标准化平台
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Sentry developer contribution Guide - configure pycharm
Win10 多种方式解决无法安装.Net3.5的问题
Rust ownership (very important)
DotNet圈里一个优秀的ORM——FreeSql
Free we media essential tools sharing