八数码之A*解决方法

学习过A*算法后,通过计算出每个节点的f值,在把队列里的节点通过对f的大小进行排列。
f=h+g
g是已经走过的步数,h为还需要最少的步数。

#include<iostream>
using namespace std;
const int MAXX = 1000000;
struct Node
{
    char tile[10];
    int pos;
    int parents;
    int g,f;
    int pre;
};
int cmp(const void*a, const void *b){
    if ((*(Node*)a).f == (*(Node*)b).f)
        return ((*(Node*)a).g == (*(Node*)b).g);
    return ((*(Node*)a).f - (*(Node*)b).f);
}
int _move[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
char pre[4] = { 'r', 'l', 'd', 'u' };
Node qu[MAXX];
int front, tail,b;
char _start[10],_end[10]="12345678x";
void init(){
    front = tail = 0;
    qu[tail++].parents = -1;
    strcpy(qu[0].tile, _start);
    qu[0].pos = strchr(_start, 'x') - _start;
    qu[0].g = 0;
    b = 0;
}

int isexit(Node node){
    for (int i = 0; i<tail; i++){
        if (strcmp(qu[i].tile, node.tile) == 0) return 1;
    }
    return 0;
}
int getF(Node node){
    int temp = 0;
    for (int i = 0; i < 9; i++){
        if (node.tile[i] != _end[i]) temp++;
    }
    return temp;
}
void show(Node temp){
    if (temp.parents != 0){
        show(qu[temp.parents]);
    }
    cout << pre[temp.pre];
}
void dfs(){
    Node temp,now;
    int x, y;
    while (tail-front>0)
    {
        qsort(qu + front, tail - front, sizeof(Node), cmp);
        now = qu[front++];
        //找到答案
        if (strcmp(now.tile, _end) == 0){
            b = 1;
            show(now);
            cout << endl;
            return;
        }
        temp.g = now.g + 1;

        for (int i = 0; i < 4; i++){
            strcpy(temp.tile, now.tile);
            x = now.pos / 3 + _move[i][0];
            y = now.pos % 3 + _move[i][1];
            if (x < 0 || x >= 3 || y < 0 || y >= 3) continue;
            temp.pos = x * 3 + y;
            temp.tile[now.pos] = now.tile[temp.pos];
            temp.tile[temp.pos] = 'x';
            if (isexit(temp)){
                continue;
            }
            temp.parents = front - 1;
            temp.pre = i;
            temp.f = temp.g+getF(temp);
            qu[tail++] = temp;
        }
    }
}
int main(){
    char str[50];
    while (gets(str)){
        int ans= 0;

        for (int i = 0; str[i]; i++){
            if (str[i] != ' ') _start[ans++] = str[i];
        }
        if (strcmp(_start, _end) == 0) cout << "lr" << endl;
        else
        {
            init();
            dfs();
            if (!b) cout << "unsolvable" << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值