#include #include #include #include #include using namespace std; typedef int TYPE; typedef vector STATE; void First(STATE& s) { for (int i = 0; i < 32; ++i){ if (s[i] % 10 == 1){ s[i] = 0; } } for (int i = 0; i < 4; ++i){ s[i * 8] = (i + 1) * 10 + 1; } } bool IsEnd(const STATE& s) { for (int i = 0; i < 4; ++i){ if (s[i * 8 + 7] != 0){ return false; } } for (int y = 0; y < 4; ++y){ for (int x = 0; x < 7; ++x){ if (s[x + y * 8] != x + 1 + (y + 1) * 10){ //cout << x << " " << y << endl; return false; } } } return true; } void Print(const STATE& s) { copy(s.begin(), s.end(), ostream_iterator(cout, " ")); cout << endl; } int Search(const STATE& start) { if (IsEnd(start)){ return 0; } set open; open.insert(start); set visited; //visited.insert(start); int count = 1; while (!open.empty()){ //cout << count << " " << open.size() << endl; set open2; for (set::iterator it_state = open.begin(); it_state != open.end(); ++it_state){ const STATE& s = *it_state; //Print(s); STATE::const_iterator it = find(s.begin(), s.end(), 0); while (it != s.end()){ //cout << "a"; int index = distance(s.begin(), it); int num = s[index - 1] + 1; if (num % 10 != 8){ int index2 = distance(s.begin(), find(s.begin(), s.end(), num)); STATE next = s; //cout << num << " " << index << " " << index2 << endl; swap(next[index], next[index2]); if (IsEnd(next)){ return count; } //Print(s); //Print(next); if (visited.find(next) == visited.end()){ //Print(s); visited.insert(next); open2.insert(next); } } it = find(it + 1, s.end(), 0); } } swap(open, open2); ++count; } return -1; } main() { int loop; cin >> loop; while (loop--){ STATE s(32); for (int y = 0; y < 4; ++y){ for (int x = 1; x <= 7; ++x){ cin >> s[y * 8 + x]; } } First(s); cout << Search(s) << endl; } }