#include <bits/stdc++.h>

using namespace std;

map<vector<int>,int> g;
vector<int> p[10];
int n;

int f[6][8]={
4,5,6,7,8,9,23,22,
10,11,12,13,14,15,21,20,
0,2,6,12,16,18,20,22,
1,3,7,13,17,19,21,23,
0,1,9,15,19,18,10,4,
2,3,8,14,17,16,11,5
};

int h[6][4]={
0,2,3,1,
18,16,17,19,
5,4,10,11,
15,9,8,14,
22,23,21,20,
6,7,13,12
};



int check(vector<int> a){
	int tot = 0;
	
	if (a[0]==a[1] && a[0]==a[2] && a[0]==a[3] ) tot++;
	if (a[6]==a[7] && a[6]==a[12] && a[6]==a[13] ) tot++;
	if (a[4]==a[5] && a[4]==a[10] && a[4]==a[11] ) tot++;
	if (a[8]==a[9] && a[8]==a[14] && a[8]==a[15] ) tot++;
	if (a[16]==a[17] && a[16]==a[18] && a[16]==a[19] ) tot++;
	if (a[20]==a[21] && a[20]==a[22] && a[20]==a[23] ) tot++;
	
	return tot;
}

int calc(int x,int y){
	int mod;
	if (y==1) mod=8;
		else mod=4;
	return (x+mod)%mod;
}

vector<int> a;

int main(){
	while (scanf("%d",&n)!=EOF){
		a.clear();
		g.clear();
		
		for (int i=0;i<24;i++){
			int x;
			scanf("%d",&x);
			a.push_back(x);
		}
		
		queue<vector<int> > q;
		g[a]=0;
		q.push(a);
		
		int ans=0;
		
		while (!q.empty()){
			vector<int> now = q.front();
			q.pop();
			
			int len = g[now];
			
			int cnt = check(now);
			ans = max(cnt,ans);
			//cout << ans << endl;
			if (ans == 6) break;
			
			
			if (g[now]==n) continue;
			
			for (int i=0;i<6;i++){
				for (int k=1;k<=1;k+=2){
					p[i] = now;
					for (int j=0;j<8;j++) p[i][f[i][calc(j+k*2,1)]] = now[f[i][j]];
					for (int j=0;j<4;j++) p[i][h[i][calc(j+k*1,2)]] = now[h[i][j]];
					
					if (g.find(p[i])==g.end()){
						q.push(p[i]);
						g[p[i]]=len+1;
					}
				}
			}
			
		}
		printf("%d\n",ans);
		
	}
	return 0;
}
