这个题可以用BFS解决。
有以下几个注意事项:
1、使用优先队列可以缩短程序运行时间。
2、要注意墙和门的相对位置(我就在这卡了一天。。sad)。
3、注意只有门和墙的位置范围是[ 1 , 199 ],Nemo的位置不一定。
4、注意没有墙和门的情况。
5、注意数组越界。
下面贴代码:
#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
struct node
{
int x,y,cut;
bool operator < (const node &b) const
{
if(cut==b.cut)
{
if(x==b.x)
{
return b.y<y;
}
else
{
return b.x<x;
}
}
else
{
return b.cut<cut;
}
}
};
const int M=405;
int main()
{
int map1[M][M],map2[M][M],x,y,d,t,n,m;
while(scanf("%d%d",&m,&n))
{
int i,j,flat,minx=1000,miny=1000,maxx=0,maxy=0;
float f1,f2;
priority_queue <struct node ,vector <struct node>,less<struct node> >qu;
if(m==-1&&n==-1)
{
break;
}
memset(map1,0,sizeof(map1));
for(j=0; j<m; j++)
{
scanf("%d%d%d%d",&x,&y,&d,&t);
x=x*2-1;
y=y*2-1;
if(d)
{
for(i=0; i<t*2; i+=2)
{
map1[y+i][x]=1;
map1[y+i+1][x]=1;
}
map1[y+2*t][x]=1;
if(x<minx)
minx=x;
if(y<miny)
miny=y;
if(x>maxx)
maxx=x;
if(y+2*t>maxy)
maxy=y+2*t;
}
else
{
for(i=0; i<t*2; i+=2)
{
map1[y][x+i]=1;
map1[y][x+i+1]=1;
}
map1[y][x+2*t]=1;
if(x<minx)
minx=x;
if(y<miny)
miny=y;
if(x+2*t>maxx)
maxx=x+2*t;
if(y>maxy)
maxy=y;
}
}
for(i=0; i<n; i++)
{
scanf("%d%d%d",&x,&y,&d);
x=x*2-1;
y=y*2-1;
if(d)
{
map1[y+1][x]=2;
}
else
{
map1[y][x+1]=2;
}
}
cin >>f1>>f2;
if (n==0 && m==0)
{
printf ("0\n");
continue;
}
else if (f1<1||f2<1||f1>199||f2>199)
{
printf ("0\n");
continue;
}
x=(int )f1*2;
y=(int)f2*2;
struct node du,dc;
du.x=x;
du.y=y;
du.cut=0;
qu.push(du);
map1[y][x]=3;
flat=0;
while(!qu.empty())
{
du=qu.top();
qu.pop();
if(du.x<minx||du.y<miny||du.x>=maxx||du.y>=maxy)
{
flat=1;
break;
}
if(du.x-1>=0)
{
if(map1[du.y][du.x-1]==2||map1[du.y][du.x-1]==0)
{
if(map1[du.y][du.x-1]==2)
{
dc.cut=du.cut+1;
}
else
{
dc.cut=du.cut;
}
map1[du.y][du.x-1]=3;
dc.x=du.x-1;
dc.y=du.y;
qu.push(dc);
}
}
if(du.x+1<=404)
{
if(map1[du.y][du.x+1]==2||map1[du.y][du.x+1]==0)
{
if(map1[du.y][du.x+1]==2)
{
dc.cut=du.cut+1;
}
else
{
dc.cut=du.cut;
}
map1[du.y][du.x+1]=3;
dc.x=du.x+1;
dc.y=du.y;
qu.push(dc);
}
}
if(du.y-1>=0)
{
if(map1[du.y-1][du.x]==2||map1[du.y-1][du.x]==0)
{
if(map1[du.y-1][du.x]==2)
{
dc.cut=du.cut+1;
}
else
{
dc.cut=du.cut;
}
map1[du.y-1][du.x]=3;
dc.x=du.x;
dc.y=du.y-1;
qu.push(dc);
}
}
if(du.y+1<=404)
{
if(map1[du.y+1][du.x]==2||map1[du.y+1][du.x]==0)
{
if(map1[du.y+1][du.x]==2)
{
dc.cut=du.cut+1;
}
else
{
dc.cut=du.cut;
}
map1[du.y+1][du.x]=3;
dc.x=du.x;
dc.y=du.y+1;
qu.push(dc);
}
}
}
if(flat)
{
printf("%d\n",du.cut);
}
else
{
printf("-1\n");
}
}
return 0;
}