stl queue 广搜求助
查看原帖
stl queue 广搜求助
375208
LawrenceSivan楼主2021/1/26 17:07
#include <bits/stdc++.h>
using namespace std;
int n,m;
struct node{
	int x,y,dep;
};
char a[5000][5000];
bool vis[5000][5000];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int ddx[8]={-1,-1,0,1,1,1,0,-1};
int ddy[8]={0,1,1,1,0,-1,-1,-1};

queue <node> q;

bool check(int cx,int cy,int hx,int hy){
	if(hx==cx&&hy==cy)return 1;
	for(int i=0;i<8;i++){
		int xx=hx+ddx[i];
		int yy=hy+ddy[i];
		while(xx>0&&xx<=n&&yy>0&&yy<=m&&a[xx][yy]=='O'){
			if(xx==cx&&yy==cy)return 1;
			xx+=ddx[i];
			yy+=ddy[i];
		}
	}
	
	return 0;
}

int bfs(int cx,int cy,int hx,int hy){
	q.push((node){hx,hy,0});
	while(!q.empty()){
		int x=q.front().x;
		int y=q.front().y;
		int step=q.front().dep;
		q.pop();
		if(check(cx,cy,x,y)==1)return step;
		for(int i=0;i<4;i++){
			int xx=x+dx[i];
			int yy=y+dy[i];
			if(xx<=0||xx>n||yy<=0||yy>m||a[xx][yy]=='X'||vis[xx][yy]==1)continue;
			
			vis[xx][yy]=1;
			
			q.push((node){xx,yy,step+1});
		}
	}
	return -1;
}
int main(){
	cin>>n>>m;
	
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>a[i][j];
		}
	}
	int cx,cy,hx,hy;
	
	while(1){
		memset(vis,0,sizeof(vis));
		
		cin>>cx>>cy>>hx>>hy;
		if(!cx&&!cy&&!hx&&!hy)break;
		
		vis[hx][hy]=1;
 		int a=bfs(cx,cy,hx,hy);		
		if(a)cout<<a<<endl;
		else{
			cout<<"Poor Harry"<<endl;
		}
		
	}
	
	return 0;
}
2021/1/26 17:07
加载中...