BFS 60分求助!
  • 板块P1141 01迷宫
  • 楼主andycode
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/7/6 11:16
  • 上次更新2024/7/6 13:54:36
查看原帖
BFS 60分求助!
907368
andycode楼主2024/7/6 11:16
#include <bits/stdc++.h>
using namespace std;
int n,m,a[1001][1001],ans[1001][1001],mark[1001][1001],d[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
void bfs(int x,int y){
	int tm[1001][1001],sum=1;
	memset(tm,0,sizeof(tm));
	queue<int> gx,gy;
	gx.push(x);
	gy.push(y);
	mark[x][y]=tm[x][y]=1;
	while(!gx.empty()){
		int fx=gx.front(),fy=gy.front();
		gx.pop(),gy.pop();
		for(int i=0;i<4;i++){
			int xx=fx+d[i][0],yy=fy+d[i][1];
			if(!mark[xx][yy] && a[fx][fy]!=a[xx][yy] && xx && yy && xx<=n && yy<=m){
				mark[xx][yy]=tm[xx][yy]=1;
				sum++;
				gx.push(xx);
				gy.push(yy);
			}
		}
	}
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			if(tm[i][j])ans[i][j]=sum;
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		string s;
		cin>>s;
		for(int j=1;j<=n;j++)a[i][j]=s[j-1]-'0';
	}
	//cout<<"YE\n";
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			if(!mark[i][j])bfs(i,j);
	//cout<<"YES\n";
	while(m--){
		int u,v;
		cin>>u>>v;
		cout<<ans[u][v]<<endl;
	}
	return 0;
}

3个TLE,2个RE

2024/7/6 11:16
加载中...