NOIP2013提高组华容道题解

题目信息

题目传送门

解题思路

在这道题中,我们肯定会想到用bfs找最短路的想法。但是,并不是所有棋子的状态都是需要记录哒(这样就会TMLE得更多啦)。在棋子移动的过程中,除了和目标棋子换的时候,空的位置已知可以和别的棋子换,所以我们只需要记录空的位置和目标棋子的位置就ok啦。

代码实现(有错待改,注释待加)

#include <bits/stdc++.h>
using namespace std;
const int N = 30;
const int dir[2][4] = {1, -1, 0, 0, 0, 0, 1, -1};
int a[N][N];
bool vis[N][N][N][N];
struct node {
    // 起始坐标以及结束坐标1
    int ex, ey, tx, ty;
    int stp;
    node() { }
    node(int _ex, int _ey, int _tx, int _ty, int _stp) {
        ex = _ex;
        ey = _ey;
        tx = _tx;
        ty = _ty;
        stp = _stp;
    }
};
queue<node> Q;
int n, m, q;
inline bool in(node u) {
    return 0 <= u.ex && u.ex < n && 0 <= u.ey && u.ey < m;
}
int main() {
    cin >> n >> m >> q;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> a[i][j];
        }
    }
    while (q--) {
        int ex, ey, sx, sy, tx, ty;
        cin >> ex >> ey >> sx >> sy >> tx >> ty;
        // 起点和终点相等,0步到达
        if (sx == tx && sy == ty) {
            cout << 0 << '\n';
            continue;
        }
        // 重置
        memset(vis, false, sizeof vis);
        // 起点标记
        vis[ex][ey][sx][sy] = true;
        while (Q.size()) {
            Q.pop();
        }
        // 起点入队
        Q.push(node(ex, ey, sx, sy, 0));
        // 结果
        int res = -1;
        while (Q.size() && res == -1) {
            node u = Q.front();
            Q.pop();
            for (int i = 0; i < 4; ++i) {
                // 下一个点
                node v = u;
                ++v.stp;
                if (v.ex + dir[0][i] == v.tx && v.ey + dir[1][i] == v.ty) {
                    swap(v.ex, v.tx);
                    swap(v.ey, v.ty);
                } else {
                    v.ex += dir[0][i];
                    v.ey += dir[1][i];
                }
                if (!in(v) || !a[v.ex][v.ey] || vis[v.ex][v.ey][v.tx][v.ty]) {
                    continue;
                }
                if (v.tx == tx && v.ty == ty) {
                    res = v.stp;
                    break;
                }
                vis[v.ex][v.ey][v.tx][v.ty] = true;
                Q.push(v);
            }
        }
        cout << res << '\n';
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒟蒻一枚

谢谢鸭~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值