EOJ 1839 恶魔之城

题目简介


给定一个迷宫和起点终点,求最快要多少步到终点以及最快的路径,不能到达输出-1。

说明


显然bfs,也因此需要开一个step数组记录步数,更新没有走过的点的step。路径还原则又需要一个数组记录这一步的上一个点,还原时从后往前递归输出即可。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 205;
int n, m, sx, sy, ex, ey, ans;
char mp[maxn][maxn];
int step[maxn][maxn];
const int dx[] = {1,-1,0,0};
const int dy[] = {0,0,1,-1};

struct node
{
    int x, y;
}a[maxn][maxn];

inline bool in(int x, int y)
{
    return x>=0 && x<n && y>=0 && y<n;
}

inline void bfs()
{
    queue<node> q;
    node u, v;
    int now = 0;
    u.x = sx; u.y = sy;
    q.push(u);
    while (!q.empty())
    {
        u = q.front(); q.pop();
        now = step[u.x][u.y];
        for (int i = 0; i < 4; ++i)
        {
            v.x = u.x+dx[i]; v.y = u.y+dy[i];
            if (in(v.x, v.y) && mp[v.x][v.y]=='.' || mp[v.x][v.y] == 'E')
                if (!step[v.x][v.y])
                {
                    a[v.x][v.y].x = u.x;
                    a[v.x][v.y].y = u.y;
                    step[v.x][v.y] = now+1;
                    if (mp[v.x][v.y] == 'E')
                    {
                        ans = step[v.x][v.y];
                        return;
                    }
                    q.push(v);
                }
        }
    }
}

inline void dfs(int x, int y)
{
    if (x!=sx || y!=sy) dfs(a[x][y].x, a[x][y].y);
    printf("%d %d\n", x, y);
}

int main()
{
    cin >> n >> m; cin.get();
    for (int i = 0; i < n; ++i)
    {
        scanf("%s", mp[i]);
        for (int j = 0; j < m; ++j)
            if (mp[i][j] == 'S')
            {
                sx = i;
                sy = j;
            }else if(mp[i][j] == 'E')
            {
                ex = i;
                ey = j;
            }
    }
    memset(step, 0, sizeof step);
    bfs();
    if (ans)
    {
        printf("%d\n", ans);
        dfs(ex, ey);
    }else printf("-1\n");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值