http://codeforces.com/problemset/problem/3/A Shortest path of the king

本文通过使用启发式搜索算法解决了八皇后问题,并实现了一个简洁的C++程序来找到从起点到终点的最短路径。该程序利用了优先队列进行节点的扩展,以确保每次选择的都是距离目标最近的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

启发式搜索写一写就搞定了,因为不存在障碍物所以每一次走的都必定是最短路中的。

#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#define MAX 100005
#define mod 998244353ll
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int cx[] = {0,0,-1,1,-1,1,-1,1};
int cy[] = {-1,1,0,0,-1,1,1,-1};
int sx, sy, ex, ey;
bool vis[10][10];
char str[][10] = { "D","U","L","R","LD","RU","LU","RD" };
struct road {
    int x, y;
    string str;
    friend bool operator<(const road& a, const road& b) {
        return abs(a.x  - ex) + abs(a.y - ey) > abs(b.x - ex) + abs(b.y - ey);
    }
};
int main() {
    freopen("a.txt", "r", stdin);
    freopen("b.txt", "w", stdout);
    string s, e;
    cin >> s >> e;
    sx = s[0] - 'a';
    sy = s[1] - '0' - 1;
    ex = e[0] - 'a';
    ey = e[1] - '0' - 1;
    if (sx == ex && sy == ey) {
        cout << 0 << endl;
        return 0;
    }
    priority_queue<road> q;
    queue<string> sq;
    q.push(road{ sx,sy,"@" });
    vis[sx][sy] = true;
    bool f = false;
    while (!q.empty()) {
        road t = q.top();
        if (t.str != "@") sq.push(t.str);
        q.pop();
        for (int i = 0; i < 8; ++i) {
            int x0 = t.x + cx[i];
            int y0 = t.y + cy[i];
            if (x0 < 0 || y0 < 0 || x0 >= 8 || y0 >= 8 || vis[x0][y0]) {
                continue;
            }
            if (x0 == ex && y0 == ey) {
                f = true;
                cout << sq.size() + 1 << endl;
                while (!sq.empty()) {
                    s = sq.front();
                    sq.pop();
                    cout << s << endl;
                }
                cout << str[i] << endl;
                break;
            }
            vis[x0][y0] = true;
            s = str[i];
            q.push(road{x0,y0,s});
        }
        if (f) break;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值