70分,想知道哪里错了,求大佬指教。
查看原帖
70分,想知道哪里错了,求大佬指教。
657356
NN1003楼主2024/4/5 13:47
//求细胞数量
#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> pi;
int n,m,a[200][200],res;
bool f[200][200];
int dxx[8]={0,1,0,-1,1,-1};
int dyy[8]={1,0,-1,0,1,-1};
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
string s;
bool check(int x,int y)
{
	if(x>=0&&x<n&&y>=0&&y<m)
	{
		return true;
	}
	return false;
}
void bfs1(int x,int y)
{
	queue<pi>q;
	f[x][y]=true;
	q.push({x,y});
	while(q.size())
	{
		auto t=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			int xx=t.first+dx[i];
			int yy=t.second+dy[i];
			if(check(xx,yy)&&a[xx][yy]!=0&&f[xx][yy]==false)
			{
				f[xx][yy]=true;
				q.push({xx,yy});
			}
		}
	}
}
void bfs(int x,int y)
{
	queue<pi>q;
	f[x][y]=true;
	q.push({x,y});
	while(q.size())
	{
		auto t=q.front();
//		cout<<"x:"<<t.first<<" "<<"y:"<<t.second<<endl;
		q.pop();
		for(int i=0;i<8;i++)
		{
			int xx=t.first+dxx[i];
			int yy=t.second+dyy[i];
			if(check(xx,yy)&&a[xx][yy]==0&&f[xx][yy]==false)
			{
//				cout<<"xx:"<<xx<<" "<<"yy:"<<yy<<endl;
				f[xx][yy]=true;
//				res++;
				q.push({xx,yy});
//				bfs(xx,yy);
			}
			if(check(xx,yy)&&a[xx][yy]!=0&&f[xx][yy]==false)
			{
				res++;
				bfs1(xx,yy);
			}
		}
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		cin>>s;
		for(int j=0;j<m;j++)
		{
			a[i][j]=s[j]-'0';
		}
	}
	int flag=0;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(i==0||i==n-1||j==0||j==m-1)
			{
				if(a[i][j]==0&&f[i][j]==false)
				{
					flag=1;
					bfs(i,j);
				}
			}
		}
	}
	if(flag==0)
		res=1;
	cout<<res<<endl;
	return 0;
}
2024/4/5 13:47
加载中...