洛谷P1451-求细胞的数量

110 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情

求细胞数量

题目描述

一矩形阵列由数字 0099 组成,数字 1199 代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。

输入格式

第一行两个整数代表矩阵大小 nnmm

接下来 nn 行,每行一个长度为 mm 的只含字符 09 的字符串,代表这个 n×mn \times m 的矩阵。

输出格式

一行一个整数代表细胞个数。

样例 #1

样例输入 #1

4 10
0234500067
1034560500
2045600671
0000000089

样例输出 #1

4

提示

数据规模与约定

对于 100%100\% 的数据,保证 1n,m1001 \le n,m \le 100。 由于本蒟蒻刚学BFSBFS,写个题解纪念一下,注意这里是四联通,就是上下左右,对角线不算,其实就是求有几个联通的非零数字块,很显然的迷宫BFSBFS问题

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string> 
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack> 
#include <cmath>
#include <iomanip>
#define int long long
#define AC return
#define Please 0
using namespace std;
const int N=110;
char a[N][N];
bool stt[N][N];
int n,m; 
typedef pair<int,int>PII;
typedef unsigned long long ull;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
bool check(int x,int y){//判断这个点是否在矩阵中(即是否合法)
	if(x>=1 && x<=n && y>=1 && y<=m) return true;
	return false;
}
inline int read(){//快读 
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9'){
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9'){
        x=x*10+ch-'0'; 
        ch=getchar();
    }
    AC x*f;
}
inline void bfs(int s,int t){
	queue<PII>q;
	q.push({s,t});
	stt[s][t]=1;
	while(q.size()){
		auto t=q.front();
		q.pop();
		int ff=t.first,ss=t.second;
		for(int i=0;i<4;i++){
			int st=ff+dx[i],en=ss+dy[i];
			if(check(st,en) && a[st][en]!='0' && stt[st][en]==0){
				stt[st][en]=1;
				q.push({st,en});
			}
		}
	}
}
signed main(){
	int cnt=0;
	memset(stt,0,sizeof stt);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>a[i][j];
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(a[i][j]!='0' && stt[i][j]==0){//这个地方不能是0且不是零不能被遍历过
				bfs(i,j);
				cnt++;//一行一行搜索,每搜索一次,连通块数量++
			}
		}
	}
	cout<<cnt<<endl;
    AC Please;
}

希望能帮助到大家(QAQQAQ)~!