#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <fstream>
#include <set>

using namespace std;

const int dy[]={-1,-1,-1,0,0,1,1,1};
const int dx[]={-1,0,1,-1,1,-1,0,1};
typedef pair<int,int> pii;
typedef pair<int,pii> sit;

int n;
char field[6][6];
pii sp;


int bfs(){
	int res=0;
	queue<sit> q[2];
	set<sit> used;
	int cur=0;
	int nxt=1;
	int ss=0;
	for(int i=0;i<n;i++)for(int j=0;j<n;j++)if(field[i][j]=='#')ss|=(1<<(i*n+j));
	q[cur].push(sit(ss,sp));
	while(q[cur].size()){
		while(q[cur].size()){
			sit csit=q[cur].front();q[cur].pop();
			if(csit.first==0)return res;
			const int fsit=csit.first;
			const pii &pp=csit.second;
			for(int l=0;l<8;l++){
				if(l==5){
					//cout<<endl;
				}
				int ny=pp.first+dy[l];
				int nx=pp.second+dx[l];
				if(ny>=0&&nx>=0&&ny<n&&nx<n&&!((fsit>>(ny*n+nx))&1)){
					int nfield=0;
					for(int i=0;i<n;i++){
						for(int j=0;j<n;j++){
							if(ny==i&&nx==j)continue;
							int cnt=0;
							for(int k=0;k<8;k++){
								int adx=j+dx[k];
								int ady=i+dy[k];
								if(ady>=0&&adx>=0&&ady<n&&adx<n)
									if(((fsit>>(ady*n+adx))&1)||(ny==ady&&nx==adx))cnt++;
							}
							if((fsit>>(i*n+j))&1){
								if(cnt==2||cnt==3)nfield|=(1<<(i*n+j));
							}
							else{
								if(cnt==3)nfield|=(1<<(i*n+j));
							}
						}
					}
					sit nsit=make_pair(nfield,make_pair(ny,nx));
					if(used.find(nsit)!=used.end())continue;
					used.insert(nsit);
					q[nxt].push(nsit);
				}
			}
		}
		swap(cur,nxt);
		res++;
	}
	return -1;
}

int main(){

	while(cin>>n&&n){
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cin>>field[i][j];
				if(field[i][j]=='@')sp.first=i,sp.second=j,field[i][j]='.';
			}
		}
		int res=bfs();
		cout<<res<<endl;
	}

	return 0;
}