#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int x[20]; vector<int>R[20]; bool used[1 << 20];
int Abs(int g) { if (g < 0) { return -g; }return g; }
int main() {
	for (int i = 0; i < 20; i++) {
		for (int j = i + 1; j < 20; j++) {
			int p1 = i / 4, p2 = i % 4;
			int q1 = j / 4, q2 = j % 4;
			if (Abs(p1 - q1) <= 1 && Abs(p2 - q2) <= 1)R[i].push_back(j);
		}
	}
	int n; cin >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < (1 << 20); j++)used[j] = false;
		for (int j = 0; j < 20; j++)cin >> x[j];
		queue<int>Q; Q.push((1 << 20) - 1); int res = 20;
		while (!Q.empty()) {
			int bit[20], d[20]; int r = Q.front(), t = 0; Q.pop();
			for (int j = 0; j < 20; j++) { bit[j] = (r / (1 << j)) % 2; t += bit[j]; }
			res = min(res, t); int cnt = 0;
			for (int j = 0; j < 20; j++) {
				if (bit[j] == 1) { d[cnt] = j; cnt++; }
			}
			for (int j = 0; j < cnt; j++) {
				for (int k = 0; k < R[j].size(); k++) {
					if (R[j][k] >= cnt)continue;
					if (x[d[j]] == x[d[R[j][k]]]) {
						int NUM = r - (1 << d[j]) - (1 << d[R[j][k]]);
						if (used[NUM] == true)continue;
						Q.push(NUM); used[NUM] = true;
					}
				}
			}
		}
		cout << res << endl;
	}
	return 0;
}