C++实现【启发式搜索】算法

  • 用优先队列实现
  • 从起点出发,需要知道终点的坐标,根据起点和终点的距离进行预估
// 'S' - 起点,'T' - 终点,'.' - 可以走的点,'*' - 最优解走过点路径,'x' - 去重已经走过了
#include <iostream>
#include <queue> //优先队列
#include <cmath>
using namespace std;

struct node {
    int x, y; //点的坐标
    int step; //到这个点走了多少步
    double dis; //预估到终点到距离
    bool operator< (const node &b) const { //默认大顶堆,需要改为小顶堆
        return this->step + this->dis > b.step + b.dis;
    }
};

int n, m; //地图大小
int sx, sy; //起点坐标
int ex, ey; //终点坐标
int mark[101][101][2]; //标记数组
int cnt;
int dir[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1}; //方向数组
char mmap[105][105]; //存放地图信息

double cal(int x, int y)
{
    int a = ex - x, b = ey - y;
    return sqrt(a * a + b * b);
}

void func(int x, int y)
{
    if ('S' == mmap[x][y]) return ;
    mmap[x][y] = '*';
    func(mark[x][y][0], mark[x][y][1]);
}

void print()
{
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            cout << mmap[i][j];
            if ('x' == mmap[i][j])
                mmap[i][j] = '&';
        }
    }
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j) {
            cin >> mmap[i][j];
            if ('S' == mmap[i][j]) //起点
                sx = i, sy = j;
            if ('T' == mmap[i][j]) //终点
                ex = i, ey = j;
        }

    priority_queue<node> que;
    que.push((node){sx, sy, 0, cal(sx, sy)});
    while (!que.empty()) {
        node tmp = que.top();
        que.pop();
        for (int i = 0; i < 8; ++i) {
            int x = tmp.x + dir[i][0], y = tmp.y + dir[i][1];
            if ('T' == mmap[x][y]) {
                func(tmp.x, tmp.y);
                print();
                cout << ++tmp.step << endl;
                return 0;
            }
            if ('.' == mmap[x][y]) {
                mark[x][y][0] = tmp.x, mark[x][y][1] = tmp.y;
                que.push((node){x, y, tmp.step + 1, cal(x, y)});
                mmap[x][y] = 'x';
                ++cnt;
            }
        }
    }
    cout << "Cant not go to end" << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值