当前位置:网站首页>Leetcode 200.岛屿数量 BFS
Leetcode 200.岛屿数量 BFS
2022-08-10 19:06:00 【Alkali!】
题目描述
岛屿数量
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
思路
直接BFS求就完事了
代码
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
vector<vector<bool>> st(grid.size()); //标记数组
for(int i=0;i<grid.size();i++)
st[i].resize(grid[0].size());
for(int i=0;i<grid.size();i++) //初始化为未访问
for(int j=0;j<grid[0].size();j++)
st[i][j]=false;
int res=0; //岛屿数量
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]=='1')
{
if(st[i][j]) continue;
else
{
res++;
bfs(st,i,j,grid); //bfs
}
}
}
return res;
}
void bfs(vector<vector<bool>>& st,int x,int y,vector<vector<char>>& gap)
{
int n=gap.size(),m=gap[0].size();
queue<pair<int,int>> q;
q.push({
x,y});
st[x][y]=true;
int dx[4]={
-1,0,1,0},dy[4]={
0,1,0,-1};
while(!q.empty())
{
auto t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int nx=t.first+dx[i],ny=t.second+dy[i];
if(nx<0||nx>=n||ny<0||ny>=m) continue; //出界
if(gap[nx][ny]=='0') continue; //没出界,但是0
if(st[nx][ny]) continue; //是1,但访问过了
q.push({
nx,ny});
st[nx][ny]=true;
}
}
}
};
边栏推荐
- DefaultSelectStrategy NIOEventLoop执行策略
- 【深度学习前沿应用】图像风格迁移
- redis 事件
- 越折腾越好用的 3 款开源 APP
- Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
- UnitTest中的Path must be within the project 问题
- 苹果字体查找
- 第四届“传智杯”全国大学生IT技能大赛(初赛A组) 补题
- pytorch使用Dataloader加载自己的数据集train_X和train_Y
- What is the upstream bandwidth and downstream bandwidth of the server?
猜你喜欢
电脑为什么会蓝屏的原因
【毕业设计】基于STM32的天气预报盒子 - 嵌入式 单片机 物联网
Linux服务器安装Redis,详细步骤。
【无标题】基于Huffman和LZ77的GZIP压缩
2022杭电多校七 Black Magic (签到)
【深度学习前沿应用】图像风格迁移
QoS服务质量六路由器拥塞管理
QoS Quality of Service Six Router Congestion Management
铁蛋白颗粒Tf包载多肽/凝集素/细胞色素C/超氧化物歧化酶/多柔比星(定制服务)
FEMRL: A Framework for Large-Scale Privacy-Preserving Linkage of Patients’ Electronic Health Rec论文总结
随机推荐
大家要的Biotin-PEG3-Br/acid/NHS ester/alcohol/amine合集分享
代理模式的使用总结
陕西CAS:1244028-50-9_Biotin-PEG3-SCO-PPh3 固体
赎金信问题答记
nfs挂载服务器,解决挂载后无法更改用户id,无法修改、写文件,文件只读权限Read-only file system等问题
【毕业设计】基于STM32的天气预报盒子 - 嵌入式 单片机 物联网
whois信息收集&企业备案信息
你不知道的浏览器页面渲染机制
flask生成路由的2种方式和反向生成url
Tf铁蛋白颗粒包载顺铂/奥沙利铂/阿霉素/甲氨蝶呤MTX/紫杉醇PTX等药物
L2-035 完全二叉树的层序遍历
状态压缩dp蒙德里安的梦想
从 GAN 到 WGAN
FPGA:基础入门按键控制蜂鸣器
优化是一种习惯●出发点是'站在靠近临界'的地方
QoS Quality of Service Eight Congestion Avoidance
常见端口及服务
3D Game Modeling Learning Route
Modern Privacy-Preserving Record Linkage Techniques: An Overview论文总结
【C#】WCF和TCP消息通信练习,实现群聊功能