当前位置:网站首页>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;
}
}
}
};
边栏推荐
- 回老家去?
- 转铁蛋白修饰蛇床子素长循环脂质体/负载三七皂苷R1的PEG-PLGA纳米粒([email protected] NPs)
- Redis persistence mechanism
- Site Architecture Detection & Chrome Plugin for Information Gathering
- What is the upstream bandwidth and downstream bandwidth of the server?
- 铁蛋白-AHLL纳米颗粒|人表皮生长因子-铁蛋白重链亚基纳米粒子(EGF-5Cys-FTH1)|铁蛋白颗粒包载氯霉素Chloramphenicol-Ferritin
- DefaultSelectStrategy NIOEventLoop执行策略
- 转铁蛋白(Tf)修饰去氢骆驼蓬碱磁纳米脂质体/香豆素-6脂质体/多柔比星脂质体
- 云渲染的应用正在扩大,越来越多的行业需要可视化服务
- 你不知道的浏览器页面渲染机制
猜你喜欢

机器学习|模型评估——AUC

DefaultSelectStrategy NIOEventLoop执行策略

Redis 持久化机制

30分钟使用百度EasyDL实现健康码/行程码智能识别

【毕业设计】基于Stm32的智能疫情防控门禁系统 - 单片机 嵌入式 物联网

uni-app 数据上拉加载更多功能

FEMRL: A Framework for Large-Scale Privacy-Preserving Linkage of Patients’ Electronic Health Rec Paper Summary

Modern Privacy-Preserving Record Linkage Techniques: An Overview论文总结

Linux服务器安装Redis,详细步骤。
[Go WebSocket] 你的第一个Go WebSocket服务: echo server
随机推荐
GBASE 8s 高可用RSS集群搭建
[教你做小游戏] 只用几行原生JS,写一个函数,播放音效、播放BGM、切换BGM
常用Anaconda安装错误解决办法Traceback (most recent call last):[通俗易懂]
What is the upstream bandwidth and downstream bandwidth of the server?
[Teach you how to make a small game] Write a function with only a few lines of native JS to play sound effects, play BGM, and switch BGM
常见端口及服务
铁蛋白颗粒负载雷替曲塞/培美曲塞/磺胺地索辛/金刚烷(科研试剂)
Keras深度学习实战(17)——使用U-Net架构进行图像分割
799. 最长连续不重复(双指针)
【CNN】刷SOTA的trick
905. 区间选点(贪心)
whois information collection & corporate filing information
【无标题】基于Huffman和LZ77的GZIP压缩
第15章_锁
803. 区间合并(贪心)左端点、右端点排序均可
QoS服务质量六路由器拥塞管理
idea汉化教程[通俗易懂]
uni-app 数据上拉加载更多功能
YOLOv3 SPP源码分析
QoS Quality of Service Eight Congestion Avoidance