题目大意是给一个图,然后给你起点和终点,以及开始所处的方向,要求你求出从起点到终点的最小步数,如果无法到达则输出-1。
这个题注意有4点:
1、它一秒可以执行2种命令,一种是向现在所面向的方向走1-3步,另外一种是向左或向右90度转向(不能向后转)。2、图中为1的是障碍物,是不允许通过的,包括边界也不能允许,这一点需要注意下。
3、对搜索进行去重操作的时候需要记录所处位置的方向,因为这个题存在方向的问题,需要注意下,可以设置数组为vis[100][100][4],4代表4个方向。
4、还可以直接做一个优化,如果终点所在的四个块存在障碍,则始终不可达。
朝某一个方向走时,如果走一步不行,后面的2,3步也不用走了。
代码:47ms
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
#define LL long long
#define N 55
#define INF 1<<29
#define CLS(x,v) memset(x,v,sizeof(x))
/**
每秒可执行一条指令,
1.向前走1,2,3 步
2.向左或向右转90度
*/
int graph[N][N];//每一点记录他右下角的状态
int vis[N][N][4];
int n,m;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//E,S,W,N
struct point{
int x,y;
int dir;
int step;
bool ok()
{
return x>0&&x<n&&y>0&&y<m;
}
bool operator ==(const point &b)const{
return x==b.x&&y==b.y;
}
bool operator <(const point&b)const{
return step>b.step;
}
}s,e;
int getdir(char* s)
{
if(s[0]=='e')return 0;
if(s[0]=='s')return 1;
if(s[0]=='w')return 2;
if(s[0]=='n')return 3;
}
int BFS()
{
if(s==e)return 0;//起点和终点相同
priority_queue<point> Q;
CLS(vis,0);
vis[s.x][s.y][s.dir]=1;
Q.push(s);
point pre,now;
while(!Q.empty())
{
pre=Q.top();
//printf("x==%d,y==%d,step==%d\n",pre.x,pre.y,pre.step);
Q.pop();
for(int i=1;i<4;i++)
{
now.x=pre.x+i*dir[pre.dir][0];
now.y=pre.y+i*dir[pre.dir][1];
if(!now.ok()||graph[now.x][now.y]||graph[now.x][now.y-1]||
graph[now.x-1][now.y]||graph[now.x-1][now.y-1])
break;
//该位置可达,并且没障碍物
now.dir=pre.dir;
if(!vis[now.x][now.y][now.dir])
{
now.step=pre.step+1;
Q.push(now);
if(now==e)return now.step;
vis[now.x][now.y][now.dir]=1;
}
}
now=pre;
now.dir++;
now.step++;
if(now.dir==4)now.dir=0;
if(!vis[now.x][now.y][now.dir])
{
Q.push(now);
vis[now.x][now.y][now.dir]=1;
}
now=pre;
now.dir--;
now.step++;
if(now.dir<0)now.dir=3;
if(!vis[now.x][now.y][now.dir])
{
Q.push(now);
vis[now.x][now.y][now.dir]=1;
}
}
return -1;
}
int main()
{
char c[10];
while(~scanf("%d%d",&n,&m)&&n&&m)
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
scanf("%d",&graph[i][j]);
scanf("%d%d",&s.x,&s.y);
scanf("%d%d",&e.x,&e.y);
scanf("%s",c);
s.dir=getdir(c);
s.step=0;
//终点不可达
if(e.x==0||e.y==0||graph[e.x][e.y]||graph[e.x-1][e.y]
||graph[e.x][e.y-1]||graph[e.x-1][e.y-1])printf("-1\n");
else printf("%d\n",BFS());
}
return 0;
}