#include<bits/stdc++.h>
using namespace std;
typedef vector<vector<char> > Area;
struct state{
  Area a;
  int c;
};
int N;
Area A;
set<Area> s;

int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,1,-1,1,-1};

bool check( const Area &a ) {
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      if( a[i][j] == '#' ) return false;
    }
  }
  return true;
}

bool outc(int x,int y){
  if( x < 0 || y < 0 || x >= N || y >= N ) return false;
  return true;
}

void get(const Area &a, int &x,int &y){
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      if( a[i][j] == '@' ){
	x = j; y  = i;
	return;
      }
    }
  }
}

Area next( const Area &a ){
  Area b;
  b.resize(N);
  for(int i=0;i<N;i++){
    b[i].resize(N);
    for(int j=0;j<N;j++){
      int cnt = 0;
      for(int k=0;k<8;k++){
	int ni = i + dy[k], nj = j + dx[k];
	if( !outc(nj,ni) ) continue;
	if( a[ni][nj] == '#' || a[ni][nj] == '@' ) cnt++;
      }
      if( a[i][j] == '#' && (cnt == 2 || cnt == 3) ) b[i][j] = '#';
      else if( a[i][j] == '.' && cnt == 3 ) b[i][j] = '#';
      else if( a[i][j] == '@' ) b[i][j] = '@';
      else b[i][j] = '.';
    }
  }
  return b;
}

void view(const Area &a){
  cout << "view" << endl;
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      cout << a[i][j];
    }
    cout << endl;
  }
}

int solve(Area a){
  if( check(a) ) return 0;
  queue<state> q;
  q.push( (state){a,0} );
  while( !q.empty() ){
    state p = q.front(); q.pop();
    int x,y;
    get(p.a,x,y);
    for(int i=0;i<8;i++){
      int ny = y + dy[i], nx = x + dx[i];
      if( !outc( ny,nx ) ) continue;
      if( p.a[ny][nx] == '.' ){
	p.a[ny][nx] = '@';
	p.a[y][x] = '.';
	Area b = next(p.a);
	if( check(b) ) return p.c + 1;
	if( s.count(b) == 0 ){
	  q.push( (state){b,p.c+1} );
	  s.insert(b);
	}
	p.a[y][x] = '@';
	p.a[ny][nx] = '.';
      }
    }
  }
  return -1;
}

int main(){
  while( cin >> N && N ){
    s.clear();
   A.resize(N);
    for(int i=0;i<N;i++){
      A[i].resize(N);
      for(int j=0;j<N;j++){
	cin >> A[i][j]; 
      }
    }
    cout <<  solve(A) << endl;
  }
}