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

using namespace std;

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

int N;
struct S {
  char g[MAX_N][MAX_N];
  int x, y;
  int cost;
  bool operator < (const S &s) const {
    if(x != s.x) return x < s.x;
    if(y != s.y) return y < s.y;
    for(int i = 0; i < N; ++i) {
      for(int j = 0; j < N; ++j) {
	if(g[i][j] != s.g[i][j]) return g[i][j] < s.g[i][j];
      }
    }
    return false;
  }
  void show() {
    for(int i = 0; i < N; ++i) {
      for(int j = 0; j < N; ++j) {
	cout << g[i][j];
      }
      cout << endl;
    }
    cout << endl;
  }
};

bool isAllFree(const S &s) {
  for(int i = 0; i < N; ++i) {
    for(int j = 0; j < N; ++j) {
      if(s.g[i][j] == '#') return false;
    }
  }
  return true;
}

void trance(const S &s, S &t, int x, int y) {
  for(int i = 0; i < N; ++i) {
    for(int j = 0; j < N; ++j) {
      if(j == x && i == y) {
	t.g[i][j] = '.';
	continue;
      }
      int cnt = 0;
      for(int k = 0; k < 8; ++k) {
	int nx = j + dx[k];
	int ny = i + dy[k];
	if(nx < 0 || nx >= N) continue;
	if(ny < 0 || ny >= N) continue;
	if(nx == x && ny == y) ++cnt;
	if(s.g[ny][nx] == '#') ++cnt;
      }
      if(s.g[i][j] == '.') {
	if(cnt == 3) t.g[i][j] = '#';
	else t.g[i][j] = '.';
      } else {
	if(cnt == 2 || cnt == 3) t.g[i][j] = '#';
	else t.g[i][j] = '.';
      }
    }
  }
}

int solve(S s) {
  queue<S> que;
  set<S> vis;
  que.push(s);
  vis.insert(s);
  while(!que.empty()) {
    s = que.front();
    que.pop();
    if(isAllFree(s)) return s.cost;
    for(int i = 0; i < 8; ++i) {
      S t;
      t.x = s.x + dx[i];
      t.y = s.y + dy[i];
      t.cost = s.cost + 1;
      if(t.x < 0 || t.x >= N) continue;
      if(t.y < 0 || t.y >= N) continue;
      if(s.g[t.y][t.x] == '#') continue;
      trance(s, t, t.x, t.y);
      if(vis.find(t) != vis.end()) continue;
      vis.insert(t);
      que.push(t);
    }
  }
  return -1;
}

int main() {
  while(cin >> N && N) {
    S s;
    s.cost = 0;
    for(int i = 0; i < N; ++i) {
      for(int j = 0; j < N; ++j) {
	cin >> s.g[i][j];
	if(s.g[i][j] == '@') {
	  s.g[i][j] = '.';
	  s.x = j;
	  s.y = i;
	}
      }
    }
    cout << solve(s) << endl;
  }
  return 0;
}