为啥错啦???
查看原帖
为啥错啦???
655195
Yannik楼主2023/7/17 16:08
#include<bits/stdc++.h>
#define N 510
using namespace std;
int n,m,x11,x22,y11,y22,g[N][N];
int dist[N][N];
bool vis[N][N];
int dx[4]= {-1,0,1,0};
int dy[4]= {0,-1,0,1};

struct node {
	int x,y;
};

void spfa(int xx,int yy) {
	queue<node> q;
	q.push({xx,yy});
	dist[xx][yy]=0;
	vis[xx][yy]=1;
	queue<int> last;
	last.push(-1);
	while(q.size()) {
		node t=q.front();
		q.pop();
		vis[t.x][t.y]=0;
		for(int i=0; i<4; i++) {
			int a=t.x+dx[i];
			int b=t.y+dy[i];
			if(a<1||a>n||b<1||b>n) continue;
			int w=0;
			int l=last.front();
			if(g[a][b]==g[t.x][t.y]&&g[a][b]==1) {
				int l=last.front();
				if(a==t.x&&b!=t.y&&l!=1) {
					w=1;
				} else if(a!=t.x&&b==t.y&&l!=0) {
					w=1;
				} else  if(a==t.x&&b!=t.y&&l==1) {
					w=0;
				} else if(a!=t.x&&b==t.y&&l==0) {
					w=0;
				}
			}
			if(dist[a][b]>dist[t.x][t.y]+w&&g[a][b]==g[t.x][t.y]&&g[a][b]==1) {

				dist[a][b]=dist[t.x][t.y]+w;
				if(!vis[a][b]) {
					vis[a][b]=1;
					q.push({a,b});
				}
				if(a==t.x&&b!=t.y&&l!=1) {
					last.push(1);
				} else if(a!=t.x&&b==t.y&&l!=0) {
					last.push(0);
				} else  if(a==t.x&&b!=t.y&&l==1) {
					last.push(1);
				} else if(a!=t.x&&b==t.y&&l==0) {
					last.push(0);
				}
			}
		}
		last.pop();
	}
}

int main() {
	memset(dist,0x3f,sizeof dist);
	cin>>n;
	for(int i=1; i<=n; i++) {
		for(int j=1; j<=n; j++) {
			char c;
			cin>>c;
			if(c=='x') {
				g[i][j]=0;
			} else if(c=='A') {
				g[i][j]=1;
				x11=i,y11=j;
			} else if(c=='B') {
				g[i][j]=1;
				x22=i,y22=j;
			} else {
				g[i][j]=1;
			}
		}
	}

	spfa(x11,y11);
	if(dist[x22][y22]!=0x3f3f3f3f) {
		cout<<dist[x22][y22]-1;
	} else {
		cout<<"-1";
	}
	return 0;
}
2023/7/17 16:08
加载中...