您的位置:首页 > 其它

swust OJ 1319: Robot in Maze

2016-04-28 09:12 381 查看
地图里面有个机器人,初始面向北方也就是上方,现在你有三个指令,向面朝的地方走一步,向左转,向右转,求到达终点的最短步数,简单BFS既可,注意状态的标记,每到一个格子就有四个方向,标记既可,代码有点冗杂。

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char map[200][200];
int use[200][200][4],n,m;
int dir[5][2]={0,0,-1,0,1,0,0,-1,0,1};
struct node
{
int x;
int y;
int count;
int di;
};
int BFS(int ix,int iy)
{
node tem;
tem.x=ix;
tem.y=iy;
tem.count=0;
tem.di=1;
use[ix][iy][1]=1;
queue<node> que;
que.push(tem);
while(!que.empty())
{
node now=que.front();
que.pop();
node next=now;
// printf("%d %d %d ",next.x,next.y,next.di);
if(map[now.x][now.y]=='T')
return now.count;
next.x=now.x+dir[now.di][0];
next.y=now.y+dir[now.di][1];
// printf("  %c \n",map[next.x][next.y]);
// printf("%d %d\n",next.x,next.y);
if(next.x>=0&&next.y>=0&&next.x<n&&next.y<m&&!use[next.x][next.y][next.di]&&map[next.x][next.y]!='#')
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}
next=now;
if(now.di==1)
{
next.di=3;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}
next=now;
next.di=4;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}

}
next=now;
if(now.di==2)
{
next.di=3;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}
next=now;
next.di=4;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}

}
next=now;
if(now.di==3)
{
next.di=2;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}
next=now;
next.di=1;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}

}
next=now;
if(now.di==4)
{
next.di=1;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}
next=now;
next.di=2;
if(!use[next.x][next.y][next.di])
{
next.count++;
use[next.x][next.y][next.di]=1;
que.push(next);
}

}

}
return -1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(use,0,sizeof(use));
int ix,iy;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",map[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(map[i][j]=='S')
{
ix=i;
iy=j;
break;
}
}
}
int ans;
ans=BFS(ix,iy);
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: