用bfs做的,没过样例QwQ
查看原帖
用bfs做的,没过样例QwQ
1252442
lucy2012楼主2024/4/14 21:54
#include<bits/stdc++.h>
using namespace std;
int n, m, vis[110][110],sum=0;
int d[4][2]={{ -1, 0},{ 0, -1},{ 1, 0},{ 0, 1}};
char ch[110][110];
struct node {
	int x, y;
} q[110];
void bfs(int x,int y){
	int head = 1,tail = 1;
	q[tail].x = x;
	q[tail].y = y;
	tail++;
	while(head < tail){
		int x1 = q[head].x;
		int y1 = q[head].y;
		vis[x1][y1] = 1;
		for(int i = 0;i < 4; i++){
			int nx = x1 + d[i][0];
			int ny = y1 + d[i][1];
			if(nx >= 0&&nx <= n&& ny >= 0&& ny <= m&& ch[nx][ny] != '0'&&!vis[nx][ny]){
				q[tail].x = nx;
				q[tail].y = ny;
				tail++;
				vis[nx][ny]=1;
			}
		}
		head++;
	}
}
int main(){
	cin>> n >> m;
	for(int i = 0; i < n; i++)
		scanf("%s", ch[i]);
	for(int i = 0; i < n; i++){
		for(int j = 0;j < m; j++){
			if(ch[i][j] != '0'&& !vis[i][j]){
				sum++;
				bfs(i, j);
			}
		}
	}
	cout<< sum;
    return 0;
}
2024/4/14 21:54
加载中...