POJ 3083 Children of the Candy Corn

解题思路:

1)靠左走,方向优先级为左->前->右->后

2)靠右走,方向优先级为右->前->左->后

2)最短路,广度优先

NULL
#include <iostream>
using namespace std;
char map[40][41];
bool visit[40][40];
const int dir[4][2]={0,1,1,0,0,-1,-1,0};
int queue[1600][2];
int w,h,sx,sy,ex,ey;
inline
bool IsOk(int x, int y, int d)
{
x
+=dir[d][0],y+=dir[d][1];
if(x>=0&&x<h&&y>=0&&y<w&&(map[x][y]=='.'||map[x][y]=='E')&&!visit[x][y])
return true;
return false;
}
int CalStep(bool IsLeft)
{
int d,tx,ty,td,curd,step;
d
= IsLeft ? 1 : 3;
step
=curd=1,tx=sx,ty=sy;
while (tx!=ex||ty!=ey)
{
td
=(curd+(4-d))%4;
if (IsOk(tx,ty,td))tx+=dir[td][0],ty+=dir[td][1],curd=td,step++;
else if(IsOk(tx,ty,curd))tx+=dir[curd][0],ty+=dir[curd][1],step++;
else if(IsOk(tx,ty,td=(curd+d)%4))tx+=dir[td][0],ty+=dir[td][1],curd=td,step++;
else td=(curd+2)%4,tx+=dir[td][0],ty+=dir[td][1],curd=td,step++;
}
return step;
}
int BFS(int s,int e)
{
int i,j,tx,ty,p;

for(i=s,p=e;i<=e;i++)
for(j=0;j<4;j++)
if(IsOk(queue[i][0],queue[i][1],j))
{
queue[
++p][0]=queue[i][0]+dir[j][0];
queue[p][
1]=queue[i][1]+dir[j][1];
visit[queue[p][
0]][queue[p][1]]=true;
if(queue[p][0]==ex&&queue[p][1]==ey)return 1;
}
return 1+BFS(e+1,p);
}
int main()
{
int i,j,n,a,b,c;
scanf(
"%d",&n);
while (n--)
{
memset(visit,
0, sizeof(visit));
scanf(
"%d %d", &w, &h);
for(i=0;i<h;i++)
{
scanf(
"%s",map[i]);
for(j=0;j<w;j++)
{
if(map[i][j]=='S')sx=i,sy=j;
else if(map[i][j]=='E')ex=i,ey=j;
}
}
queue[
0][0]=sx,queue[0][1]=sy;
a
=CalStep(true),b=CalStep(false);
c
=BFS(0,0)+1;
printf(
"%d %d %d\n", a, b, c);
}
return 0;
}

 

posted on 2010-12-15 12:38  ltang  阅读(238)  评论(0编辑  收藏  举报

导航