#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
using namespace std;
struct List{
	char s[30];
};
struct List list;
struct comp{
	bool operator() (const List& a, const List& b) const{
		if(strcmp(a.s,b.s)<0)	return true;
		return false;
	}
};

map <List,int,comp> MAP;
int op[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}},M[10][10],ini[10][10],N,MAX;

bool dfs(int level);

int main()
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	
	int n,i,j,stx,sty,ans,tmpx,tmpy,all,t;
	char ss[10];
	while(scanf(" %d",&N)==1 && N){
		gets(ss);
		memset(ini,0,sizeof(ini));
		for(n=0;n<N;n++){
			gets(ss);
			for(i=0;i<N;i++){
				if(ss[i]=='@')
					ini[n][i] = 2;
				else if(ss[i]=='#')
					ini[n][i] = 1;
			}
		}
		for(MAX=all=0;MAX<=50;MAX++){
			for(i=0;i<N;i++)
				for(j=0;j<N;j++)
					M[i][j] = ini[i][j];
			MAP.clear();
			if(dfs(0)){
				all = 2;
				break;
			}
		}
		if(all==2)
			printf("%d\n",MAX);
		else
			printf("-1\n");
	}
}
bool dfs(int level)
{
	int i,j,stx,sty,tmpx,tmpy,all,t,next[10][10],x,y,k;
	if(level>MAX)
		return false;
	for(i=0;i<30;i++)
		list.s[i] = '\0';
	for(i=all=k=0;i<N;i++){
		for(j=0;j<N;j++){
			if(M[i][j]==1){
				list.s[k++] = '#';
				all++;
			}
			else if(M[i][j]==2){
				stx = i;
				sty = j;
				list.s[k++] = '@';
			}
			else
				list.s[k++] = '.';
		}
	}
	list.s[k++] = level;
	if(all==0)
		return true;
	if(MAP.find(list)!=MAP.end())
		return false;
	MAP[list] = 1;
	for(i=0;i<N;i++)
		for(j=0;j<N;j++)
			next[i][j] = M[i][j];
	for(t=0;t<8;t++){
		tmpx = stx+op[t][0];
		tmpy = sty+op[t][1];
		if(tmpx<0 || tmpx>=N || tmpy<0 || tmpy>=N)
			continue;
		if(next[tmpx][tmpy]==1)
			continue;
		next[tmpx][tmpy] = 2;
		next[stx][sty] = 0;
		for(i=0;i<N;i++){
			for(j=0;j<N;j++){
				if(next[i][j]==2)
					M[i][j] = 2;
				else{
					int tmp = 0;
					for(k=0;k<8;k++){
						x = i+op[k][0];
						y = j+op[k][1];
						if(x<0 || x>=N || y<0 || y>=N)
							continue;
						if(next[x][y]!=0)
							tmp++;
					}
					if(next[i][j]==1){
						if(tmp==2 || tmp==3)
							M[i][j] = 1;
						else
							M[i][j] = 0;
					}
					else{
						if(tmp==3)
							M[i][j] = 1;
						else
							M[i][j] = 0;
					}
				}
			}
		}
		if(dfs(level+1))
			return true;
		next[tmpx][tmpy] = 0;
		next[stx][sty] = 2;
	}
	return false;
}