### constant

W = 4
H = 5
WH = W * H

NBRS = [[1, 0], [-1, 1], [0, 1], [1, 1]]

### subroutines

def min_cards(cards)
  cl = cards.length
  return 0 if cl == 0

  min_c = cl

  for y0 in (0...H)
    for x0 in (0...W)
      id0 = y0 * W + x0
      break if id0 >= cl

      crd0 = cards[id0]

      for nbr in NBRS
        x1 = x0 + nbr[0]
        y1 = y0 + nbr[1]
        next if x1 < 0 || x1 >= W || y1 >= H

        id1 = y1 * W + x1
        break if id1 >= cl

        crd1 = cards[id1]
        next if crd0 != crd1

        cards.delete_at(id1)
        cards.delete_at(id0)

        c = min_cards(cards)
        return 0 if c == 0

        cards.insert(id0, crd0)
        cards.insert(id1, crd1)

        min_c = c if min_c > c
      end
    end
  end

  min_c
end

### main

n = gets.to_i

n.times do
  cards = []
  H.times do
    cards += gets.split.map(&:to_i)
  end
  #p cards

  min_c = min_cards(cards)
  puts min_c
end