题目大意:有一张矩阵地图,是由一堆1*1的小个子组成的
,有一个机器人可以再格子的交界处运动。机器人要占四个格子
机器人可以左转或是右转或是前进1,2,3个单位,这些操作的完成时间都是1s。现在机器人在一个起点,有一个终点。问机器人从起点到达终点的最短用时。没有解输出-1.
注意:对于前进,如果前进一个格子会遇见障碍物,那么是无法前进两个格子或是三个格子的。
我刚开始WA的地方,感觉也是一个很容易WA的地方:我把遇见障碍无和这个格子已经访问过了混在一起了。比如如果前进两个格子,这个格子访问过,我就跳出了,就不给他前进三个格子的可能性(实际上这时前进三个格子的地方很可能没访问过而且可以走)
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 57;
int D[maxn][maxn];
int Sta[2];
int End[2];
int dir;
bool Vis[maxn][maxn][4];
//分析:在每个节点都可以进行转弯(除了原有方向)
//转弯后可以前进三种距离
//所以对于每个点有四种状态对应在这个点的四种面向
//每一秒可以左转或是右转或是前进1,2,3米(前提是这种状态之前没有访问过,并且可以进行)
//使用bfs进行搜索
//判断是否可以前进
// 机器人坐标与网格坐标的关系:表示上方,左边有多少网格
int Ocp[4][2] = { {-1,-1},{-1,0},{0,0},{0,-1} };//四个格子对应的坐标,左上角的格子顺时针下来
//对应点的四个方向化格子部位1且不为边界
//0123表示朝向为北东南西
int Op[4][2] = { -1,0,0,1,1,0,0,-1 };
typedef struct node
{
int _dir;
int _loc[2];
int cen;
node(int d, int x, int y, int c){
_dir = d;
cen = c;
_loc[0] = x;
_loc[1] = y;
}
node() {
}
}node;
node stack[10007];
int M, N;
bool check(int dir, int &x, int &y,bool flag)
{
if (flag)
{
x= x + Op[dir][0];
y= y + Op[dir][1];
}
for (int i = 0; i < 4; i++)
{
int tx = x + Ocp[i][0];
int ty = y + Ocp[i][1];
if (tx < 0 || ty < 0 || tx >= M || ty >= N || D[tx][ty] == 1)
return false;
}
return true;
}
int main()
{
while (true)
{
cin >> M >> N;//M行N列
if (M == 0 && N == 0)
break;
memset(Vis, 0, sizeof(Vis));
for (int i = 0; i<M; i++)
{
for (int j = 0; j<N; j++)
{
scanf("%d", &D[i][j]);
}
}
string s;
cin >> Sta[0] >> Sta[1] >> End[0] >> End[1] >> s;
if (s=="north")
{
dir = 0;
}
else if (s == "east")
{
dir = 1;
}
else if (s == "south")
{
dir = 2;
}
else
{
dir = 3;
}
//手写堆栈实现
int first = 0;
int last = 0;
node B(dir, Sta[0], Sta[1], 0);
stack[last++] = B;
int ans = -1;
Vis[Sta[0]][Sta[1]][dir] = 1;
if (check(dir, Sta[0], Sta[1],false))
{
while (first != last)
{
node then = stack[first++];
int x = then._loc[0];
int y = then._loc[1];
int c = then.cen;
int d = then._dir;
if (x == End[0] && y == End[1])
{
ans = c;
break;
}
if (Vis[x][y][(d + 1) % 4] == 0)
{
Vis[x][y][(d + 1) % 4] = 1;
node nn((d + 1) % 4, x, y, c + 1);
stack[last++] = nn;
}
if (Vis[x][y][(d - 1+4) % 4] == 0)
{
Vis[x][y][(d - 1+4) % 4] = 1;
node nn((d - 1+4) % 4, x, y, c + 1);
stack[last++] = nn;
}
for (int i = 1; i <= 3; i++)
{
if (check(d, x, y,true))//如果可以前进
{
if (!Vis[x][y][d])//判断这个地方有没有到达过
{
node nn(d, x, y, c + 1);
Vis[x][y][d] = 1;
stack[last++] = nn;
}
}
else//前进不合法,直接跳出
{
break;
}
}
}
}
std::cout << ans << endl;
}
return 0;
}
还剩999道。。。加油!!!