超时求调
  • 板块P1141 01迷宫
  • 楼主I_AM_AKer
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/6/27 21:36
  • 上次更新2024/6/28 10:45:34
查看原帖
超时求调
1260420
I_AM_AKer楼主2024/6/27 21:36

#3 TLE

#include<bits/stdc++.h>
using namespace std;

const int N=1e3+10;
int n,m;
bool a[N][N];

int _visit[N][N];

int read() {
  int x = 0, w = 1;
  char ch = 0;
  while (ch < '0' || ch > '9') {  
    if (ch == '-') w = -1;       
    ch = getchar();               
  }
  while (ch >= '0' && ch <= '9') {  
    x = x * 10 + (ch - '0');  
    ch = getchar();  
  }
  return x * w;  
}
void write(int x) {
  
  if (x > 9) write(x / 10);  
  putchar(x % 10 + '0');  
}

int bfs(int x,int y){
	
	int cnt=0;
	bool vis[N][N]={0};
	queue<pair<int,int>>q,que;
	q.push({x,y});
	que.push({x,y});
	vis[x][y]=1;
	while(!q.empty()){
		pair<int,int> flag=q.front();
		q.pop();
		cnt++;
		int i=flag.first;
		int j=flag.second;
		if(i-1>0&&a[i-1][j]==!a[i][j]&&!vis[i-1][j]){
			q.push({i-1,j});
			que.push({i-1,j});
			vis[i-1][j]=1;
		}
		if(i+1<=n&&a[i+1][j]==!a[i][j]&&!vis[i+1][j]){
			q.push({i+1,j});
			que.push({i+1,j});
			vis[i+1][j]=1;
		}
		if(j-1>0&&a[i][j-1]==!a[i][j]&&!vis[i][j-1]){
			q.push({i,j-1});
			que.push({i,j-1});
			vis[i][j-1]=1;
		}
		if(j+1<=n&&a[i][j+1]==!a[i][j]&&!vis[i][j+1]){
			q.push({i,j+1});
			que.push({i,j+1});
			vis[i][j+1]=1;
		}
	}
	while(!que.empty()){
		int i=que.front().first,j=que.front().second;
		_visit[i][j]=cnt;
		que.pop();
	}
	return cnt;
}

signed main(){
//	ios::sync_with_stdio(false);
//	cin.tie(NULL);
//	cout.tie(NULL);
	cin>>n>>m;
	for(int j=1;j<=n;j++){
		for(int i=1;i<=n;i++){
			char s;
			cin>>s;
			if(s=='0'){
				a[j][i]=0;
			}			
			else a[j][i]=1;
		}
	}
	for(int i=1;i<=m;i++){
		int x,y;
		x=read();
		y=read();
		if(_visit[x][y]!=0){
			write( _visit[x][y]);
			cout<<"\n";
		}
		else {
			cout<<bfs(x,y)<<"\n";
		}
	}
	return 0;
}
2024/6/27 21:36
加载中...