zoukankan      html  css  js  c++  java
  • 八数码问题 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;
    }
  • 相关阅读:
    二,数据类型与流程控制语句
    一,cmd指令集与变量
    web第九天,浮动与定位
    web第八天,PS切图与float浮动
    web第七天,标签分类
    web第六天,CSS优先级与盒子模型
    web第五天复合样式与选择器
    web第四天,CSS基础
    web第三天 表单与css基础
    装饰器
  • 原文地址:https://www.cnblogs.com/hznumqf/p/12363845.html
Copyright © 2011-2022 走看看