题意 : 求从一个点走到迷宫的一边上最短的步数,每次如果可以转弯走就必须转弯走(即不能直走),无法转弯则考虑向前走。
思路 : 求最短步数, 所以广搜, 因为每一个点都会有可能从4个方向进来的可能, 所以开一个三维记忆数组vis[x][y][k]标记这种可能是否已经走过。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 110;
struct sss
{
int x, y, p;
int s;
}q[maxn*maxn*4], e;
int maze[maxn][maxn], n, m;
int vis[maxn][maxn][4];
int sx, sy;
char ss[maxn];
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
bool IsEnd(int a, int b)
{
if (a == 1 || b == 1 || a == n || b == m)return true;
else return false;
}
int bfs()
{
if (IsEnd(sx, sy))return 0;
int head, tail, x, y, s, p;
memset(vis, 0, sizeof(vis));
for (int i = 0; i < 4; i++)vis[sx][sy][i] = 1;
head = tail = 0;
e.x = sx; e.y = sy; e.s = 0; e.p = -1;
q[head] = e;
while (head <= tail)
{
int fg = 0;
x = q[head].x; y = q[head].y;
s = q[head].s; p = q[head].p;
for (int i = 0; i < 4; i++) if (p < 0 || (p&1) != (i&1))
{
e.x = x + dir[i][0];
e.y = y + dir[i][1];
if (maze[e.x][e.y] == 0)continue; fg = 1;
if (vis[e.x][e.y][i])continue;
e.s = s + 1; e.p = i;
if (IsEnd(e.x, e.y))return e.s;
q[++tail] = e; vis[e.x][e.y][i] = 1;
}
if (fg == 0)
{
e.x = x + dir[p][0];
e.y = y + dir[p][1];
if (maze[e.x][e.y] != 0 && vis[e.x][e.y][p] == 0)
{
e.s = s + 1; e.p = p;
if (IsEnd(e.x, e.y))return e.s;
q[++tail] = e; vis[e.x][e.y][p] = 1;
}
}
++head;
}
return -1;
}
int main()
{
int T;
scanf("%d", &T);
for (int cas = 1; cas <= T; cas++)
{
scanf("%d%d", &n, &m);
memset(maze, 0, sizeof(maze));
for (int i = 1; i <= n; i++)
{
scanf("%s", ss);
for (int j = 0; j < m; j++)
if (ss[j] == '#')
{
maze[i][j+1] = 0;
}
else
{
maze[i][j+1] = 1;
if (ss[j] == '@')
{
sx = i; sy = j + 1;
}
}
}
printf("%d\n", bfs());
}
return 0;
}