HDOJ 2364 Escape (bfs)

题意 : 求从一个点走到迷宫的一边上最短的步数,每次如果可以转弯走就必须转弯走(即不能直走),无法转弯则考虑向前走。

思路 : 求最短步数, 所以广搜, 因为每一个点都会有可能从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;
}



PS :   忘记了一开始就是在边上的这一可能,wa了好几次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值