#include #include #include using namespace std; struct State { public: int mat[4][8]; int x[4], y[4]; int operator <(State c) const { for (int i = 0; i < 4; i++) { for (int j = 0; j < 8; j++) { if (mat[i][j] < c.mat[i][j]) return 1; if (mat[i][j] > c.mat[i][j]) return 0; } } return 0; } }; typedef set Stset; int main() { int N; ifstream is("gap.txt"); is >> N; for (int i = 0;i < N; i++) { State s0; int ng = 0; for (int i = 0; i < 4; i++) { s0.mat[i][0] = i*10+11; for (int j = 1; j < 8; j++) { is >> s0.mat[i][j]; if (s0.mat[i][j] % 10 == 1) { s0.x[ng] = j; s0.y[ng] = i; ng++; s0.mat[i][j] = 0; } } } Stset stats, oldstats; stats.insert(s0); for (int steps = 0;; steps++) { if (stats.empty()) { cout << -1 << endl; break; } Stset nextstats; // cout << steps << '\t' << stats.size() << endl; for(Stset::iterator ii = stats.begin(); ii != stats.end(); ii++) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 7; j++) { if (ii->mat[i][j] != 11+i*10+j) goto nomatch; } } cout << steps << endl; goto nextdata; nomatch: for (int i = 0; i < 4; i++) { int back = ii->mat[ii->y[i]][ii->x[i]-1]; if (back == 0 || back % 10 == 7) continue; int x, y; for (y = 0; y < 4; y++) { for (x = 1; x < 8; x++) { if (back+1 == ii->mat[y][x]) goto matched; } } cout << "bug"; cout << back << endl; matched: State tmp = *ii; tmp.mat[tmp.y[i]][tmp.x[i]] = back+1; tmp.mat[y][x] = 0; tmp.x[i] = x; tmp.y[i] = y; if (oldstats.find(tmp) != oldstats.end()) continue; nextstats.insert(tmp); oldstats.insert(tmp); } } stats = nextstats; } nextdata: ; } }