题目大意:马琳要去寻找被困在迷宫的尼莫,迷宫有墙啊有门啊。问马琳最少要走过多少门才能找到尼莫。
思路:刚看到题目不知道该怎么建图。后来干脆就繁琐的建掉。
直接用一个MP的结构体记录每条边的状态:起点和终点,还有它是门还是墙。
然后因为马琳在外面。如果对马琳进行搜索的话,首先就要找到入口,如果有好多入口的话就不好办了。所以我选择对尼莫进行搜索。如果他旁边找不到地图中记录的边的话。就意味着他走出来了。
这样的话就只需要用一个二维判重数组就够了。还有,我把门记录在墙之后,所以我优先搜门,如果无路可走的话就无法扩展。
因为我的没想到更好办法建图,所以每次都要搜索边,耗时巨大,只能 ORZ 1300MS 低空掠过
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n,m;
int v[500][500];
int dx[] = {0,0,-1,1};
int dy[] = {1,-1,0,0};
struct mp
{
int sx,sy;
int ex,ey;
int w; //记录它是门还是墙
}map[1000005];
struct node
{
double x,y;
int step;
};
int findroad(int x1,int y1,int x2,int y2)
{
if(x1==x2)
{
for(int i=m+n;i>=1;i--) //优先搜门
if(x1==map[i].sx && y1>=map[i].sy && x2==map[i].ex && y2<=map[i].ey)return i;
}
else if(y1==y2)
{
for(int i=m+n;i>=1;i--)
if(y1==map[i].sy && y2==map[i].ey && x1>=map[i].sx && x2<=map[i].ex)return i;
}
return -1;
}
void bfs(node t)
{
memset(v,0,sizeof(v));
queue<node>Q;
node w,e;
Q.push(t);
int vx=(int)t.x;
int vy=(int)t.y;
v[vx][vy]=1;
while(!Q.empty())
{
w=Q.front();
Q.pop();
for(int k=0;k<4;k++)
{
e=w;
double xx = e.x + dx[k];
double yy = e.y + dy[k];
int x1,x2,y1,y2,vx,vy;
if(k==0){x1=(int)e.x;y1=(int)ceil(e.y);x2=(int)ceil(e.x);y2=(int)ceil(e.y);} //这是对它的方向判断 寻找边的坐标 不同方向是不一样的
else if(k==1){x1=(int)e.x;y1=(int)e.y;y2=(int)e.y;x2=(int)ceil(e.x);}
else if(k==2){x1=x2=(int)e.x;y1=(int)e.y;y2=(int)ceil(e.y);}
else if(k==3){x1=x2=(int)ceil(e.x);y1=(int)e.y;y2=(int)ceil(e.y);}
//cout<<"---------"<<endl;
int r=findroad(x1,y1,x2,y2);
// printf("x1=%d y1=%d x2=%d y2=%d\n",x1,y1,x2,y2);
// printf("r = %d\n",r);
if(r<0) //如果没有找到边的话就意味着走出来了
{
printf("%d\n",e.step);
return;
}
vx=(int)xx;
vy=(int)yy;
// printf("vx = %d vy = %d vxy = %d\n",vx,vy,v[vx][vy]);
if(map[r].w==0 && v[vx][vy]==0)
{
e.x=e.x+dx[k];
e.y=e.y+dy[k];
v[vx][vy]=1;
e.step++;
Q.push(e);
// printf("x = %lf y = %lf\n",e.x,e.y);
}
}
}
printf("-1\n");
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF && n!=-1 && m!=-1)
{
int tx,ty,d,l;
node t;
for(int i=1;i<=n;i++)
{
scanf("%d%d%d%d",&tx,&ty,&d,&l);
if(d)
{
map[i].sx=map[i].ex=tx;
map[i].sy=ty;
map[i].ey=ty+l;
map[i].w=1;
}
else
{
map[i].sy=map[i].ey=ty;
map[i].sx=tx;
map[i].ex=tx+l;
map[i].w=1;
}
}
for(int i=n+1;i<=m+n;i++)
{
scanf("%d%d%d",&tx,&ty,&d);
if(d)
{
map[i].sx=map[i].ex=tx;
map[i].ey=ty+1;
map[i].sy=ty;
map[i].w=0;
}
else
{
map[i].sy=map[i].ey=ty;
map[i].sx=tx;
map[i].ex=tx+1;
map[i].w=0;
}
}
scanf("%lf%lf",&t.x,&t.y);
t.step=0;
if (n==0 && m==0)
printf ("0\n");
else if (t.x<0||t.y<0||t.x>199||t.y>199)
printf ("0\n");
else
bfs(t);
}
return 0;
}