当前位置:网站首页>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;
}
}
}
};
边栏推荐
- 烟雾、空气质量、温湿度…自己徒手做个环境检测设备
- 803. 区间合并(贪心)左端点、右端点排序均可
- Solution for thread not gc-safe when Rider debugs ASP.NET Core
- The servlet mapping path matching resolution
- 905. 区间选点(贪心)
- FPGA:基础入门按键控制蜂鸣器
- About npm/cnpm/npx/pnpm and yarn
- The Biotin-PEG3-Br/acid/NHS ester/alcohol/amine collection that everyone wants to share
- IIC通信协议总结[通俗易懂]
- LeetCode·26.删除有序数组中的重复项·双指针
猜你喜欢
『牛客|每日一题』岛屿数量
端口探测详解
[Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
主动信息收集
Keras深度学习实战(17)——使用U-Net架构进行图像分割
- [email protected])纳米酶"/>
血红素-金纳米颗粒(Heme-AuNP)复合纳米酶|金纳米颗粒核多孔空心碳纳米球壳([email protected])纳米酶
测试/开发程序员值这么多钱么?“我“不会愿赌服输......
【初学必备】3d游戏建模入门基础知识
redis 事件
转铁蛋白Tf功能化β-榄香烯-雷公藤红素/紫杉醇PLGA纳米粒/雷公藤甲素脂质体(化学试剂)
随机推荐
DefaultSelectStrategy NIOEventLoop执行策略
【luogu CF1534F2】Falling Sand (Hard Version)(性质)(dfs)(线段树 / 单调队列 / 贪心)
今日份bug,点击win10任务栏视窗动态壁纸消失的bug,暂未发现解决方法。
3D游戏建模学习路线
ARouter使用自定义注解处理器,自动生成跳转Activity的代码,避免手动填写和管理path
常见端口及服务
7-2 乒乓人训练大师(双指针)
flask的配置文件
转铁蛋白修饰长春新碱-粉防己碱脂质体|转铁蛋白修饰共载紫杉醇和金雀异黄素脂质体(试剂)
spark学习笔记(九)——sparkSQL核心编程-DataFrame/DataSet/DF、DS、RDD三者之间的转换关系
测试/开发程序员值这么多钱么?“我“不会愿赌服输......
铁蛋白颗粒负载雷替曲塞/培美曲塞/磺胺地索辛/金刚烷(科研试剂)
状态压缩dp蒙德里安的梦想
QoS Quality of Service Six Router Congestion Management
西安Biotin-PEG8-IA_IA-PEG8-生物素供应商
杭电多校七 1003-Counting Stickmen(组合数学)
Hangdian Multi-School Seven 1003-Counting Stickmen (Combination Mathematics)
弘玑Cyclone与风变科技达成战略合作:优势互补聚焦数字化人才培养
【初学必备】3d游戏建模入门基础知识
含有PEG 间隔基和一个末端伯胺基团(CAS:1006592-62-6)化学试剂