当前位置:网站首页>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;
}
}
}
};
边栏推荐
- Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
- servlet映射路径匹配解析
- 几行深度学习代码设计包含功能位点的候选免疫原、酶活性位点、蛋白结合蛋白、金属配位蛋白
- Linux服务器安装Redis,详细步骤。
- Tf铁蛋白颗粒包载顺铂/奥沙利铂/阿霉素/甲氨蝶呤MTX/紫杉醇PTX等药物
- cordova 安装错误 Command failed: powershell 解决方法
- 基于TCP的聊天系统
- 【毕业设计】基于STM32的天气预报盒子 - 嵌入式 单片机 物联网
- 优雅退出在Golang中的实现
- [Go WebSocket] 你的第一个Go WebSocket服务: echo server
猜你喜欢
MATLAB设计,FPGA实现,联合ISE和Modelsim仿真的FIR滤波器设计
3D Game Modeling Learning Route
[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
电脑为什么会蓝屏的原因
uni-app 数据上拉加载更多功能
转铁蛋白(TF)修饰紫杉醇(PTX)脂质体(TF-PTX-LP)|转铁蛋白(Tf)修饰姜黄素脂质体
Introduction to 3 d games beginners essential 】 【 modeling knowledge
Redis 持久化机制
We used 48h to co-create a web game: Dice Crush, to participate in international competitions
几行深度学习代码设计包含功能位点的候选免疫原、酶活性位点、蛋白结合蛋白、金属配位蛋白
随机推荐
几行深度学习代码设计包含功能位点的候选免疫原、酶活性位点、蛋白结合蛋白、金属配位蛋白
pytorch使用Dataloader加载自己的数据集train_X和train_Y
赎金信问题答记
优雅退出在Golang中的实现
Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
FEMRL: A Framework for Large-Scale Privacy-Preserving Linkage of Patients’ Electronic Health Rec Paper Summary
[Go WebSocket] Your first Go WebSocket server: echo server
运维面试题(每日一题)
【SemiDrive源码分析】【MailBox核间通信】51 - DCF_IPCC_Property实现原理分析 及 代码实战
IIC通信协议总结[通俗易懂]
代理模式的使用总结
电脑开不了机是什么原因?
工业基础类—利用xBIM提取IFC几何数据
【luogu CF1534F2】Falling Sand (Hard Version)(性质)(dfs)(线段树 / 单调队列 / 贪心)
第14章_MySQL事务日志
机器学习|模型评估——AUC
【greenDao】Cannot access ‘org.greenrobot.greendao.AbstractDaoSession‘ which is a supertype of
Random函数用法
Pt/CeO2单原子纳米酶|[email protected] NPs纳米酶|碳纳米管负载铂颗粒纳米酶|白血病拮抗多肽修饰的FeOPtPEG复合纳米酶
799. 最长连续不重复(双指针)