当前位置:网站首页>一本通1329 细胞(广度优先搜索)
一本通1329 细胞(广度优先搜索)
2022-07-27 05:04:00 【竹林居士-】
原题链接
http://ybt.ssoier.cn:8088/problem_show.php?pid=1329
【题目描述】
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:
阵列:
4 10 0234500067 1034560500 2045600671 0000000089
有4个细胞。
【输入】
第一行为矩阵的行n和列m;
下面为一个n×m的矩阵。
【输出】
细胞个数。
【输入示范】
4 10 0234500067 1034560500 2045600671 0000000089
【输出示范】
4
审题
相邻的非零数字为一个细胞。统计细胞个数即可
步骤
1.定义变量
#include<iostream>
#include<queue>
using namespace std;
int a[4][2]={
{1,0},{-1,0},{0,1},{0,-1}};
int n,m,res=0;
char s[1000][1000];
int mk[1000][1000];
struct node{ //结构体
int x;
int y;
};2.定义广搜函数
void bfs(int x,int y)
{
queue<node>q;
q.push((node){x,y});
while(q.size())
{
node t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int xx=t.x+a[i][0];
int yy=t.y+a[i][1];
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&s[xx][yy]!='0'&& mk[xx][yy]==0)
{
mk[xx][yy]=1;
q.push((node){xx,yy});
} }
}
return;
}主函数:
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>s[i][j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s[i][j]!='0' && mk[i][j]==0)
{
res++;
mk[i][j]=1;
bfs(i,j);
}
}
}
cout<<res<<endl;
return 0;
}完整代码
#include<iostream>
#include<queue>
using namespace std;
int a[4][2]={
{1,0},{-1,0},{0,1},{0,-1}};
int n,m,res=0;
char s[1000][1000];
int mk[1000][1000];
struct node{
int x;
int y;
};
void bfs(int x,int y)
{
queue<node>q;
q.push((node){x,y});
while(q.size())
{
node t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int xx=t.x+a[i][0];
int yy=t.y+a[i][1];
if(xx>=1 && xx<=n && yy>=1&& yy<=m && s[xx][yy]!='0'&& mk[xx][yy]==0)
{
mk[xx][yy]=1;
q.push((node){xx,yy});
} }
}
return;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>s[i][j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s[i][j]!='0' && mk[i][j]==0)
{
res++;
mk[i][j]=1;
bfs(i,j);
}
}
}
cout<<res<<endl;
return 0;
}边栏推荐
猜你喜欢
随机推荐
后台实现sku 管理
分享一道关于#define的选择题(内含#define在预编译时的替换规则,程序环境和预处理相关知识)
Initial C language -- the function of keyword static
软件测试面试题(重点)
分享一道关于变量的选择题(内含全局变量、局部变量、变量的作用域、生命周期知识点)
Redis transaction
Introduction and management of heap memory in C language
初识C语言——字符串+转义字符+注释
我的第一篇博客
First knowledge of C language - string + escape character + comment
登录到主页功能实现
JS中如何判断一个属性是属于实例对象还是继承于构造函数
页面的配置
Time complexity and space complexity
JS中apply、call、bind的区别
Hi3516DV300环境搭建
Introduction to C language
Day4 --- Flask 蓝图与Rest-ful
pytorch安装新坑
C language elementary level -- branch statement (if, switch)









