八数码问题 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; }