//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#include <queue>

using namespace std;

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);

int idx(PII p){
  return p.first*10+p.second+11;
}

int main(){
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  int N; cin >> N;
  REP(n,N){
	VI xs(32);
	REP(i,4){
	  REP(j,7) cin >> xs[i*8+j+1];
	  xs[i*8] = 0;
	}

	REP(i,32)
	  if(xs[i]%10 == 1){
		swap(xs[i], xs[(xs[i]/10-1)*8]);
	  }

	map<VI,int> memo;
	queue<VI> q;
	q.push(xs);
	memo[xs] = 0;

	int ans = -1;
	while(!q.empty()){
	  xs = q.front(); q.pop();
	  bool ok = true;
	  REP(y,4) REP(x,7)
		if(xs[y*8+x] != y*10+x+11){
		  ok = false;
		  x = y = 100;
		}
	  if(ok){
		ans = memo[xs];
		break;
	  }

	  int d = memo[xs];
	  REP(y,4) FOR(x,1,8){
		int idx = y*8+x;
		if(xs[idx] == 0 && xs[idx-1]%10 < 7){
		  REP(ty,4) FOR(tx,1,8){
			int tidx = ty*8+tx;
			if(xs[idx-1]+1 == xs[tidx]){
			  VI tmp = xs;
			  swap(tmp[idx], tmp[tidx]);

			  if(!memo.count(tmp)){
				q.emplace(tmp);
				memo[tmp] = d + 1;
			  }
			  ty = tx = 100;
			}
		  }
		}
	  }
	}
	cout << ans << endl;
  }

  return 0;
}