P2199 最后的迷宫
#include <bits/stdc++.h>
using namespace std;
int n,m;
char a[130][130];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
bool vis[130][130];
struct Stament{
int x;
int y;
int step;
};
void bfs(Stament st,int ex,int ey){
queue<Stament> q;
Stament now,next;
st.step=0;
vis[st.x][st.y]=1;
q.push(st);
while(!q.empty()){
now=q.front();
int t=now.x;
for(int i=now.x;i<n;i++){
if(a[i][now.y]=='X') break;
if(now.y==ey&&i==ex){
cout<<now.step<<endl;
return ;
}
}
for(int i=now.x;i>=0;i--){
if(a[i][now.y]=='X') break;
if(now.y==ey&&i==ex){
cout<<now.step<<endl;
return ;
}
}
for(int i=now.y;i<m;i++){
if(a[now.x][i]=='X') break;
if(now.x==ex&&i==ey){
cout<<now.step<<endl;
return ;
}
}
for(int i=now.y;i>=0;i--){
if(a[now.x][i]=='X') break;
if(now.x==ex&&i==ey){
cout<<now.step<<endl;
return ;
}
}
int xx=now.x,yy=now.y;
while(xx<n&&yy<m){
if(a[xx][yy]=='X') break;
if(xx==ex&&yy==ey){
cout<<now.step<<endl;
return ;
}
xx++,yy++;
}
xx=now.x,yy=now.y;
while(xx>=0&&yy>=0){
if(a[xx][yy]=='X') break;
if(xx==ex&&yy==ey){
cout<<now.step<<endl;
return ;
}
xx--,yy--;
}
xx=now.x,yy=now.y;
while(xx<n&&yy>=0){
if(a[xx][yy]=='X') break;
if(xx==ex&&yy==ey){
cout<<now.step<<endl;
return ;
}
xx++,yy--;
}
xx=now.x,yy=now.y;
while(xx>=0&&yy<m){
if(a[xx][yy]=='X') break;
if(xx==ex&&yy==ey){
cout<<now.step<<endl;
return ;
}
xx--,yy++;
}
for(int i=0;i<4;i++){
next.x=now.x+dx[i];
next.y=now.y+dy[i];
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&vis[next.x][next.y]!=1&&a[next.x][next.y]=='O'){
next.step=now.step+1;
vis[next.x][next.y]=1;
q.push(next);
}
}
q.pop();
}
cout<<"Poor Harry"<<endl;
return ;
}
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++) cin>>a[i][j];
}
int sx,sy,ex,ey;
while(cin>>sx>>sy>>ex>>ey){
if(sx==0&&sy==0&&ex==0&&ey==0){
return 0;
}
Stament t;
t.x=sx-1,t.y=sy-1;
memset(vis,0,sizeof(vis));
bfs(t,ex-1,ey-1);
}
return 0;
}