#include #include #include using namespace std; #define card(x,y) ((x+1) * 10 + (y + 1)) #define EMPTY 7 struct table_t { char c[4][8]; }; bool operator <(table_t a, table_t b){ for(int i=0; i<4; i++){ for(int j=1; j<8; j++){ if(a.c[i][j] < b.c[i][j]){ return true; }else if(a.c[i][j] > b.c[i][j]){ return false; } } } return false; } typedef set lt; typedef lt::iterator ltit; lt ls1, ls2, *now, *next; void out(const table_t t){ for(int i=0; i<4; i++){ for(int j=0; j<8; j++){ cout << (int)(t.c[i][j]) << " "; } cout << endl; } cout << endl << flush; } void swap() { lt *temp = now; now = next; next = temp; next->clear(); } bool check(table_t &t) { for(int i=0; i<4; i++){ for(int j=1; j<7; j++){ if(t.c[i][j] != card(i,j)){ return false; } } } return true; } int hotspot(const table_t t) { /* for(int i=0; i<4; i++){ for(int j=1; j<7; j++){ if(t.c[i][j] == EMPTY){ return card(i,j); }else if(t.c[i][j] != card(i,j)){ break; } } } */ return -1; } table_t move(table_t t, int c){ table_t ret; for(int i=0; i<4; i++){ ret.c[i][0] = card(i, 0); for(int j=1; j<8; j++){ if(t.c[i][j] == c){ ret.c[i][j] = EMPTY; }else if(t.c[i][j-1] == c-1){ ret.c[i][j] = c; }else{ ret.c[i][j] = t.c[i][j]; } } } return ret; } int solve(table_t t){ if(check(t)){ return 0; } // cout << "----" << endl; ls1.clear(); ls2.clear(); now = &ls1; next = &ls2; next->clear(); next->insert(t); for(int loop=0; loop < 10000; loop++){ swap(); // cout << "#" << loop << ":" << now->size() << endl << flush; if(now->size() == 0){return -1; } for(ltit p = now->begin(); p != now->end(); p++){ // out(*p); int hs = hotspot(*p); if(hs >= 0){ // cout << "HS: " << hs << endl; table_t table = move(*p, hs); if(check(table)){ return loop+1; } next->insert(table); }else{ for(int i=0; i<4; i++){ for(int j=1; j<8; j++){ if(p->c[i][j] == EMPTY && ((p->c[i][j-1] % 10) < 7)){ // cout << "FOUND" << endl; table_t table = move(*p, p->c[i][j-1] + 1); if(check(table)){ return loop+1; } next->insert(table); } } } } } } return -2; } int main(void) { ifstream cin("gap.txt"); int N; cin >> N; while(N-- > 0) { table_t table; for(int i = 0; i < 4; i++) { table.c[i][0] = card(i,0); for(int j = 1; j < 8; j++) { int x; cin >> x; if((x % 10) == 1){ table.c[i][j] = EMPTY; }else{ table.c[i][j] = x; } } } // out(table); cout << solve(table) << endl; } }