#include<stdio.h>
#include<string.h>
struct node
{
int x;
int y;
int step;
}a[1600];
char maze[50][50];
int count,d;
int visit[40][40];
int fx[]= {0,1,0,-1};
int fy[]= {1,0,-1,0};
int fr[]= {1,0,3,2};
int fl[]= {3,0,1,2};
int dir[4][2]={1,0,-1,0,0,1,0,-1};
char sx,sy,ex,ey;
int w,h;
void dfsleft(int d,int x,int y)
{
int tx,ty;
if(x==ex&&y==ey)
{
printf("%d ",count);
return ;
}
count++;
for(int j=0;j<4;j++)
{
int i=(d+fl[j])%4;
tx=x+fx[i];
ty=y+fy[i];
if(tx>=0&&tx<h&&ty>=0&&ty<w&&maze[tx][ty]!='#')
{
dfsleft(i,tx,ty);
return;
}
}
}
void dfsright(int d,int x,int y)
{
int tx,ty;
if(x==ex&&y==ey)
{
printf("%d ",count);
return ;
}
for(int j=0;j<4;j++)
{
int i=(d+fr[j])%4;
tx=x+fx[i];
ty=y+fy[i];
if(tx>=0&&tx<h&&ty>=0&&ty<w&&maze[tx][ty]!='#')
{
count++;
dfsright(i,tx,ty);
return;
}
}
}
void bfs(int sx,int sy)
{
a[0].x=sx;
a[0].y=sy;
a[0].step=0;
int front=0;
int rear=1;
int tx,ty;
memset(visit,0,sizeof(visit));
visit[sx][sy]=1;
while(front<rear)
{
node cur,exchange;
cur=a[front++];
if(cur.x==ex&&cur.y==ey)
{
printf("%d\n",cur.step+1);
}
for(int i=0;i<4;i++)
{
tx=cur.x+dir[i][0];
ty=cur.y+dir[i][1];
if(tx>=0&&tx<h&&ty>=0&&ty<w&&visit[tx][ty]==0&&maze[tx][ty]!='#')
{
visit[tx][ty]=1;
exchange.x=tx;
exchange.y=ty;
exchange.step=cur.step+1;
a[rear++]=exchange;
}
}
}
}
int main()
{
int cases=0;
scanf("%d",&cases);
while(cases--)
{
scanf("%d%d",&w,&h);
for(int i=0;i<h;i++)
{
scanf("%s",maze[i]);
for(int j=0;j<w;j++)
{
if(maze[i][j]=='S')
{
sx=i;
sy=j;
}
if(maze[i][j]=='E')
{
ex=i;
ey=j;
}
}
}
if(sx==0)d=0;
if(sx==h-1)d=2;
if(sy==0)d=1;
if(sy==w-1)d=3;
count=1;
dfsleft(d,sx,sy);
count=1;
dfsright(d,sx,sy);
bfs(sx,sy);
}
return 0;
}
Children of the Candy Corn
最新推荐文章于 2021-12-01 18:19:20 发布