• 八数码问题 IDA*搜索


    #include<iostream>
    #include<string>
    #include<cmath>
    #include<cstring>
    #include<vector>
    #include<map>
    #include<set>
    #include<algorithm>
    #include<queue>
    #include<stack>
    #include<sstream>
    #include<cstdio>
    #define INF 0x3f3f3f3f
    //const int maxn = 1e6 + 5;
    const double PI = acos(-1.0);
    typedef long long ll;
    using namespace std;
    
    char ss[15];
    int ans[4][4] = {
        {0,0,0,0},
        {0,1,2,3},
        {0,8,0,4},
        {0,7,6,5}
    };
    int a[5][5];
    int k, judge;
    int dx[] = { 0,1,-1,0 };
    int dy[] = { 1,0,0,-1 };
    
    int check() {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (ans[i][j] != a[i][j]) return 0;
            }
        }
        return 1;
    }
    
    int test(int step) {
        int cnt = 0;
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (ans[i][j] != a[i][j]) {
                    if (++cnt + step > k) return 0;
                }
            }
        }
        return 1;
    }
    
    void A_star(int step, int x, int y, int pre) {
        if (step == k) {
            if (check()) judge = 1; return;
        }
        if (judge) return;
        for (int i = 0; i < 4; i++) {
            int xx = x + dx[i], yy = y + dy[i];
            if (xx < 1 || xx>3 || yy < 1 || yy>3 || pre + i == 3) continue;
            swap(a[x][y], a[xx][yy]);
            if (test(step) && !judge) A_star(step + 1, xx, yy, i);
            swap(a[x][y], a[xx][yy]);
        }
    }
    
    int main() {
        int x, y;
        scanf("%s",ss);
        for (int i = 0; i < 9; i++) {
            a[i / 3 + 1][i % 3 + 1] = ss[i] - '0';
            if (ss[i] - '0' == 0) x = i / 3 + 1, y = i % 3 + 1;
        }
        if (check()) {
            printf("0\n");
        }
        else {
            while (++k) {
                A_star(0, x, y, -1);
                if (judge) {
                    printf("%d", k);
                    break;
                }
            }
        }
        return 0;
    }
  • 相关阅读:
    Ubuntu下配置Viw Tab键缩进格数
    Windows文件传给Ubuntu出现乱码问题
    [Luogu] P4948 数列求和
    [Luogu]P1286 两数之和
    [Luogu]P2717 寒假作业
    [Luogu]P5110 块速递推
    Breeze魔兽编程交流论坛
    #pragma 预处理指令详解
    Api Hook 细析(一)
    CMS(网站内容管理系统)有哪些?
  • 原文地址:https://www.cnblogs.com/hznumqf/p/12363845.html
Copyright © 2020-2023  润新知