估价函数其实就是与目标状态有几个不同。。。
迭代启发搜索。
#include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <fstream> #include <iostream> #include <queue> #define rep(i, l, r) for(int i = l; i <= r; i++) #define down(i, l, r) for(int i = l; i >= r; i--) #define maxn 123 #define MAX 1<<30; using namespace std; int n[6][6], k, x, y; char s[9]; int F() { int c = 0; rep(i, 1, 5) if (n[1][i] == 0) c++; rep(i, 2, 5) if (n[2][i] == 0) c++; rep(i, 4, 5) if (n[3][i] == 0) c++; if (n[4][5] == 0) c++; rep(i, 1, 5) if (n[5][i] == 1) c++; rep(i, 1, 4) if (n[4][i] == 1) c++; rep(i, 1, 3) if (n[3][i] == 1) c++; if (n[2][1] == 1) c++; return c; } bool Search(int x, int y, int c) { if (!c && x == 3 && y == 3 && !F()) return true; if (c < F()-1) return false; //int now = F(), a; int a; if (x > 2 && y > 1) { a = n[x-2][y-1]; n[x-2][y-1] = n[x][y]; n[x][y] = a; if (Search(x-2, y-1, c-1)) return true; a = n[x-2][y-1]; n[x-2][y-1] = n[x][y]; n[x][y] = a; } if (x > 1 && y > 2) { a = n[x-1][y-2]; n[x-1][y-2] = n[x][y]; n[x][y] = a; if (Search(x-1, y-2, c-1)) return true; a = n[x-1][y-2]; n[x-1][y-2] = n[x][y]; n[x][y] = a; } if (x < 5 && y > 2) { a = n[x+1][y-2]; n[x+1][y-2] = n[x][y]; n[x][y] = a; if (Search(x+1, y-2, c-1)) return true; a = n[x+1][y-2]; n[x+1][y-2] = n[x][y]; n[x][y] = a; } if (x < 4 && y > 1) { a = n[x+2][y-1]; n[x+2][y-1] = n[x][y]; n[x][y] = a; if (Search(x+2, y-1, c-1)) return true; a = n[x+2][y-1]; n[x+2][y-1] = n[x][y]; n[x][y] = a; } if (x < 4 && y < 5) { a = n[x+2][y+1]; n[x+2][y+1] = n[x][y]; n[x][y] = a; if (Search(x+2, y+1, c-1)) return true; a = n[x+2][y+1]; n[x+2][y+1] = n[x][y]; n[x][y] = a; } if (x < 5 && y < 4) { a = n[x+1][y+2]; n[x+1][y+2] = n[x][y]; n[x][y] = a; if (Search(x+1, y+2, c-1)) return true; a = n[x+1][y+2]; n[x+1][y+2] = n[x][y]; n[x][y] = a; } if (x > 2 && y < 5) { a = n[x-2][y+1]; n[x-2][y+1] = n[x][y]; n[x][y] = a; if (Search(x-2, y+1, c-1)) return true; a = n[x-2][y+1]; n[x-2][y+1] = n[x][y]; n[x][y] = a; } if (x > 1 && y < 4) { a = n[x-1][y+2]; n[x-1][y+2] = n[x][y]; n[x][y] = a; if (Search(x-1, y+2, c-1)) return true; a = n[x-1][y+2]; n[x-1][y+2] = n[x][y]; n[x][y] = a; } return false; } int main() { int t; scanf("%d", &t); while (t--) { rep(i, 1, 5) { scanf("%s", s); rep(j, 1, 5) if (s[j-1] == '*') x = i, y = j, n[i][j] = 0; else if (s[j-1] == '0') n[i][j] = 0; else n[i][j] = 1; } k = 0; while (k <= 15) if (Search(x, y, k)) break; else k++; if (k == 16) k = -1; printf("%d ", k); } }