#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define W 4
#define H 5
#define NOTEXIST -1
int ans;
int board[H][W];
int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
struct point{
    int x, y;
};

void remove_cards(point a, point b){
    board[a.y][a.x] = NOTEXIST;
    board[b.y][b.x] = NOTEXIST;
    vector<int> v, u;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (board[i][j] == NOTEXIST) {
                u.push_back(NOTEXIST);
                continue;
            }
            v.push_back(board[i][j]);
        }
    }
    for (int i = 0; i < u.size(); i++) {
        v.push_back(u[i]);
    }
    for (int i = 0; i < v.size(); i++) {
        board[i / 4][i % 4] = v[i];
    }
}

bool invalid(int mx, int my){
    return (mx < 0 || mx >= W || my < 0 || my >= H);
}

void dfs(int count){
    ans = max(ans, count);
    if (ans == 20) {
        return;
    }
    int board_cp[H][W];
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            if (board[y][x] == NOTEXIST) {
                break;
            }
            for (int i = 0; i < 8; i++) {
                int mx = x + dx[i];
                int my = y + dy[i];
                if (invalid(mx, my)) {
                    continue;
                }

                if (board[my][mx] == NOTEXIST) {
                    continue;
                }
                
                if (board[y][x] == board[my][mx]) {
                    memcpy(board_cp, board, sizeof(board));
                    remove_cards(point({x, y}), point({mx, my}));
                    dfs(count + 2);
                    memcpy(board, board_cp, sizeof(board));
                }
            }
        }
    }
    return;
}

int main()
{

    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < H; j++) {
            for (int k = 0; k < W; k++) {
                cin >> board[j][k];
            }
        }
        ans = 0;
        dfs(0);
        cout << 20 - ans << endl;
    }
    return 0;
}