有没有大佬帮忙看看,全部输出-1
查看原帖
有没有大佬帮忙看看,全部输出-1
661913
liwenxi1145144444楼主2022/12/24 16:43
#include<bits/stdc++.h>
using namespace std;
int n,ax,ay,dx,dy;
char mapp[101][101];
bool vis[101][101];
struct node{
	int x,y,step,prev;
};
queue<node> q;
int go[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs(int x,int y){
	q.push({x,y,0,0});
	vis[x][y]=1;
	while(!q.empty()){
		node tmp=q.front();
		q.pop();
		if(tmp.x==dx&&tmp.y==dy){
			cout<<tmp.step;
			exit(0);
		}
		for(int i=0;i<4;i++){
			int xx=tmp.x+go[i][0];
			int yy=tmp.y+go[i][1];
			if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&!vis[xx][yy]){
				if(tmp.prev==0){
					vis[xx][yy]=1;
					if(mapp[xx][yy]=='-'){
						q.push({xx,yy,tmp.step+1,1});
					}else{
						q.push({xx,yy,tmp.step+1,2});
					}
				}else if(tmp.prev==1){
					if(mapp[xx][yy]=='+'){
						q.push({xx,yy,tmp.step+1,2});
						vis[xx][yy]=1;
					}
				}else{
					if(mapp[xx][yy]=='-'){
						q.push({xx,yy,tmp.step+1,1});
						vis[xx][yy]=1;
					}
				}
			}
		}
	}
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>mapp[i][j];
			if(mapp[i][j]=='A'){
				ax=i;
				ay=j;
			}
			if(mapp[i][j]=='B'){
				dx=i;
				dy=j;
			}
		}
	}
	bfs(ax,ay);
	cout<<-1;
	return 0;
} 
2022/12/24 16:43
加载中...