#include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
#define D10 fixed<<setprecision(10)
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-10;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }

/*--------------------template--------------------*/

int main()
{
	int n;
	cin >> n;
	while (n--)
	{
		vector<vi> v(4, vi(8));
		auto goal = v;
		REP(i, 4)REP(j, 7) goal[i][j] = (i+1) * 10 + j + 1;
		REP(i, 4)FOR(j, 1, 8)
		{
			cin >> v[i][j];
			if (v[i][j] % 10 == 1)
			{
				v[v[i][j] / 10 - 1][0] = v[i][j];
				v[i][j] = 0;
			}
		}
		queue<pair<vector<vi>, int>> que;
		set<vector<vi>> st;
		que.push(make_pair(v, 0));
		bool f = true;
		while (que.size())
		{
			auto tmp = que.front().first;
			int cnt = que.front().second;
			que.pop();
			if (tmp == goal)
			{
				f = false;
				cout << cnt << endl;
				break;
			}
			REP(i, 4)FOR(j, 1, 8)
			{
				if (tmp[i][j] == 0 && tmp[i][j - 1] != 0 && tmp[i][j - 1] % 10 != 7)
				{
					auto nx = tmp;
					int t = tmp[i][j - 1] + 1;
					REP(ii, 4)REP(jj, 8)
					{
						if (tmp[ii][jj] == t)
						{
							nx[ii][jj] = 0;
						}
					}
					nx[i][j] = t;
					if (st.count(nx)) continue;
					else
					{
						st.insert(nx);
						que.push(make_pair(nx, cnt + 1));
					}
				}
			}
		}
		if (f) puts("-1");
	}
	return 0;
}