Mn Zn求助
查看原帖
Mn Zn求助
947881
liuyize549330楼主2024/5/22 19:08

过样例但0pts,求助

#include <bits/stdc++.h>
#define int long long 
using namespace std;
const int N=801,M=801;
struct ree{
	int x,y;
	int k;
};
struct re{
	int x,y,s;
};
queue<re> q;
int n,m;
char c[N][M];
int vis1[N][M],vis2[N][M];
int fx[]={0,1,0,-1,0};
int fy[]={0,0,1,0,-1};
int bfs(){
	while(!q.empty()) q.pop();
	for(int i=1;i<=800;i++){
		for(int j=1;j<=800;j++) c[i][j]=' ';
	}
	memset(vis1,0,sizeof vis1);
	memset(vis2,0,sizeof vis2);
	cin>>n>>m;
	int mi,mj;
	int gi,gj;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>c[i][j];
			if(c[i][j]=='Z') q.push((re){i,j,0});
			if(c[i][j]=='M') mi=i,mj=j;
			if(c[i][j]=='G') gi=i,gj=j;
		}
	} 
	q.push((re){mi,mj,1});
	q.push((re){gi,gj,1});
	while(!q.empty()){
		re x=q.front();
		q.pop();
//		if(c[x.x][x.y]=='Z'){
//			for(int i=1;i<=4;i++){
//				int tx=x.x+fx[i];
//				int ty=x.y+fy[i];
//				if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&c[tx][ty]!='Z'){
//					q.push((re){tx,ty,0});
//					if(c[tx][ty]=='M'||c[tx][ty]=='G') return -1;
//					c[tx][ty]='Z';
//				}
//			}	
//		}
		if(c[x.x][x.y]=='Z'){
			queue<ree> qq;
			qq.push((ree){x.x,x.y,1});
			while(!qq.empty()){
				ree xx=qq.front();
				qq.pop();
				if(xx.k==3){
					q.push((re){x.x,x.y,0});
					continue;
				}
				for(int i=1;i<=4;i++){
					int tx=xx.x+fx[i];
					int ty=xx.y+fy[i];
					if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&c[tx][ty]!='Z'){
						qq.push((ree){xx.x,xx.y,xx.k+1});
						if(c[tx][ty]=='M'||c[tx][ty]=='G') return -1;
						c[tx][ty]='Z';
					}
				}
			}
		}
		if(c[x.x][x.y]=='M'){
			queue<ree> qq;
			qq.push((ree){x.x,x.y,1});
			while(!qq.empty()){
				ree xx=qq.front();
				qq.pop();
				if(xx.k==4){
					q.push((re){x.x,x.y,x.s+1});
					continue;
				}
				for(int i=1;i<=4;i++){
					int tx=xx.x+fx[i];
					int ty=xx.y+fy[i];
					if(tx<1||ty<1||tx>n||ty>m||c[tx][ty]=='X'||c[tx][ty]=='Z'||vis1[tx][ty]) continue;
					if(c[tx][ty]=='G') return x.s;
					vis1[tx][ty]=1;
					qq.push((ree){tx,ty,xx.k+1});
					c[tx][ty]='G';
					c[xx.x][xx.y]='.';
				}
			}
		}
		if(c[x.x][x.y]=='G'){
			for(int o=1;o<=4;o++){
				int i=x.x+fx[o];
				int j=x.y+fy[o];
				if(i<1||i>n||j<1||j>m||c[i][j]=='X'||c[i][j]=='Z'||vis2[i][j]) continue;
				if(c[i][j]=='M') return x.s;
				q.push((re){i,j,x.s+1});
				vis2[i][j]=1;
				c[i][j]='G';
				c[x.x][x.y]='.';
			}	
		}
	}
	return -1;
}
signed main(){
	int T;
	cin>>T;
	while(T--){
		cout<<bfs()<<endl;
	}
}
2024/5/22 19:08
加载中...