#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Info{
	void set(int arg_task,int arg_num){
		task = arg_task;
		num = arg_num;
	}
	int task,num;
};

struct Data{
	Info unit_table[5];
	int clock,min_task,max_task;
};

char table[5][20];
int loc[20];
int N;

void func(){

	for(int i = 0; i < 5; i++)scanf("%s",table[i]);

	for(int i = 0; i < N; i++){
		for(int k = 0; k < 5; k++){
			if(table[k][i] == 'X'){
				loc[i] = k;
				break;
			}
		}
	}

	Data first;
	for(int unit = 0; unit < 5; unit++){
		if(table[unit][0] == 'X'){
			first.unit_table[unit].set(0,0);
		}else{
			first.unit_table[unit].set(BIG_NUM,BIG_NUM);
		}
	}
	first.clock = 1;
	first.min_task = 0;
	first.max_task = 0;

	queue<Data> Q;
	Q.push(first);

	int count;
	bool collide;

	while(!Q.empty()){

		Data new_data;
		for(int unit = 0; unit < 5; unit++)new_data.unit_table[unit].set(BIG_NUM,BIG_NUM);

		collide = false;
		count = 0;
		new_data.min_task = BIG_NUM,new_data.max_task = -BIG_NUM;

		for(int task = Q.front().min_task; task <= Q.front().max_task; task++){
			for(int unit = 0; unit < 5; unit++){
				if(Q.front().unit_table[unit].task == task){

					if(Q.front().unit_table[unit].num < N-1){
						new_data.min_task = min(new_data.min_task,task);
						new_data.max_task = max(new_data.max_task,task);

						int next_loc = loc[Q.front().unit_table[unit].num+1];
						if(new_data.unit_table[next_loc].task == BIG_NUM){
							count++;
							new_data.unit_table[next_loc].task = task;
							new_data.unit_table[next_loc].num = Q.front().unit_table[unit].num+1;

							if(task == 9 && Q.front().unit_table[unit].num+1 == N-1){
								printf("%d\n",Q.front().clock+1);
								return;
							}
						}else{
							collide = true;
							break;
						}
					}
					break;
				}
			}
			if(collide)break;
		}
		if(collide){
			Q.pop();
			continue;
		}

		if(new_data.unit_table[loc[0]].task == BIG_NUM && new_data.max_task < 9){
			Data new_data_add;
			for(int unit = 0; unit < 5; unit++){
				new_data_add.unit_table[unit].set(new_data.unit_table[unit].task,new_data.unit_table[unit].num);
			}
			new_data_add.unit_table[loc[0]].set(new_data.max_task+1,0);
			new_data_add.clock = Q.front().clock+1;
			new_data_add.min_task = new_data.min_task;
			new_data_add.max_task = new_data.max_task+1;

			Q.push(new_data_add);
		}

		if(count > 0){
			new_data.clock = Q.front().clock+1;
			Q.push(new_data);
		}
		Q.pop();
	}
}


int main(){

	while(true){
		scanf("%d",&N);
		if(N == 0)break;

		func();
	}

	return 0;
}