/* ACM ICPC Japan Domestic 2000 Problem B: Patience by Naoyuki Tamura (tamura@kobe-u.ac.jp) */ import java.io.*; import java.util.*; public class B { static boolean dbg = false; static DataInputStream in = new DataInputStream(System.in); static int N = -1; static int row = 5; static int col = 4; static int c[]; static int penalty; static void debug(String msg) { if (dbg) System.err.print(msg); } static boolean read() throws Exception { String line = null; debug("# Enter\n"); if (N < 0) { line = in.readLine(); N = Integer.parseInt(line); } if (N == 0) return false; readCard(); N--; return true; } static void readCard() throws Exception { String line = null; StringTokenizer st; c = new int[row*col]; int k = 0; for (int i = 0; i < row; i++) { line = in.readLine(); st = new StringTokenizer(line); for (int j = 0; j < col; j++) c[k++] = Integer.parseInt(st.nextToken()); } } static void showCard(int c[]) { for (int k = 0; k < c.length; k++) { if (k % col == 0) debug("| "); debug(c[k] + " "); } debug("|\n"); } static void try_remove(int c[], int k0, int dk) { if (penalty == 0) return; if (k0+dk < c.length && c[k0] == c[k0+dk]) { int new_c[] = new int[c.length-2]; int k; for (k = 0; k < k0; k++) new_c[k] = c[k]; for (k = k0+1; k < k0+dk; k++) new_c[k-1] = c[k]; for (k = k0+dk+1; k < c.length; k++) new_c[k-2] = c[k]; solve(new_c); } } static void solve(int c[]) { if (c.length < penalty) penalty = c.length; if (penalty == 0) return; for (int k0 = 0; k0 < c.length-1; k0 += col) { int k = k0; try_remove(c, k, 1); try_remove(c, k, col); try_remove(c, k, col+1); for (k = k0+1; k < k0+col-1; k++) { try_remove(c, k, 1); try_remove(c, k, col-1); try_remove(c, k, col); try_remove(c, k, col+1); } k = k0+col-1; try_remove(c, k, col-1); try_remove(c, k, col); } } public static void main(String args[]) { if (args.length > 0) dbg = true; try { while (read()) { penalty = c.length; solve(c); System.out.println(penalty); } } catch (Exception e) { e.printStackTrace(); } } }