P1126 机器人搬重物
题目省略
题目分析:
这道题主体是bfs,一眼就能看出来,但是比较让人难受的是处理的几个小细节。
- 图的转化问题
注意题目给的是网格图的形式,而机器人走的是格点,而且格点之间的转化也是需要注意的(够够的)。 - 方向问题
NSWE方向的转化表示,不会有人用字符表示的,因为还要和方向前进联系 - 前进问题(是否会撞墙)
常规的bfs处理,不过需要的矩阵可能多
另外:
在一定条件下慎用 “%” 取模,有可能就WA那几个点,因为取模之后可能出现0,但是需要的是1;
代码
#include<iostream>
using namespace std;
#include<iomanip>
#include<string>
#include<algorithm>
#include<stack>
#include<map>
#include<queue>
#include<vector>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<cstdio>
typedef unsigned long long ULL;
typedef long long LL;
typedef long L;
const int maxn=60;
int n,m;
int Map[maxn][maxn];
int Ma[maxn][maxn];
int Ma1[maxn][maxn];
int sx,sy,ex,ey;
string tfx;
int sfx;
int dx[]={0, 1,-1, 0, 0};
int dy[]={0, 0, 0, 1,-1};
int fxc[]={0,1,2,3,4};
int abc[]={0,1,2,1,0};
//x,y表示的是行和列
void fxchange()
{
if(tfx[0]=='N')
{
sfx=1;
return;
}
else if(tfx[0]=='S')
{
sfx=3;
return;
}
else if(tfx[0]=='W')
{
sfx=4;
return;
}
else if(tfx[0]=='E')
{
sfx=2;
return;
}
}
void Machange()
{
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
if(Map[i][j]==1)
{
Ma[i-1][j]=1;
Ma[i][j-1]=1;
Ma[i-1][j-1]=1;
Ma[i][j]=1;
}
}
}
}
struct node
{
int x,y;
int fx;
int time;
};
void bfs()
{
queue<node> q;
node first;
first.x=sx;
first.y=sy;
first.fx=sfx;
first.time=0;
q.push(first);
node u,d;
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=1;i<=4;++i)
{
int zhuan=abc[i];
int fangx=u.fx+i;
if(fangx>4)
fangx-=4;
int fxi;
if(fangx==1)
fxi=2;
else if(fangx==2)
fxi=3;
else if(fangx==3)
fxi=1;
else if(fangx==4)
fxi=4;
for(int j=1;j<=3;++j)
{
int lsx=u.x+dx[fxi]*j;
int lsy=u.y+dy[fxi]*j;
if( lsx>=n || lsx<=0 || lsy>=m || lsy<=0 || (lsx==sx&&lsy==sy) || Ma[lsx][lsy]==1 )
{
break;
}
if( (u.time+zhuan+1<Ma1[lsx][lsy] || Ma1[lsx][lsy]==0) && Ma[lsx][lsy]==0 )
{
d.x=lsx;
d.y=lsy;
d.fx=fangx;
d.time=u.time+zhuan+1;
Ma1[lsx][lsy]=d.time;
q.push(d);
}
}
}
}
if(Ma1[ex][ey]==0 && (sx!=ex || sy!=ey) )
{
printf("-1\n");
}
else
printf("%d\n",Ma1[ex][ey]);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
scanf("%d",&Map[i][j]);
}
}
scanf("%d %d %d %d",&sx,&sy,&ex,&ey);
cin >> tfx;//这里用字符之前死活不行,莫名的后缀,换了string
fxchange();
Machange();
bfs();
return 0;
}