#include <cassert>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;

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


inline int encode(const vector<string> &state) {
	const int n = state.size();

	int index;
	int res = 0;

	for(int y = 0; y < n; ++y) {
		for(int x = 0; x < n; ++x) {
			res = (res << 1) + (state[y][x] == '#' ? 1 : 0);
			if(state[y][x] == '@') {
				index = x + y * n;
			}
		}
	}

	res |= (index << (n * n));
	return res;
}

inline vector<string> decode(int code, int n) {
	vector<string> res(n, string(n, '.'));
	for(int y = n - 1; y >= 0; --y) {
		for(int x = n - 1; x >= 0; --x) {
			if(code & 1) res[y][x] = '#';
			code >>= 1;
		}
	}

	res[code / n][code % n] = '@';
	return res;
}

inline bool out(int x, int y, int n) {
	return x < 0 || y < 0 || x >= n || y >= n;
}

inline vector<string> update(const vector<string> &state) {
	const int n = state.size();
	vector<string> res(n, string(n, '.'));

	for(int y = 0; y < n; ++y) {
		for(int x = 0; x < n; ++x) {
			if(state[y][x] == '@') {
				res[y][x] = '@';
				continue;
			}

			int cnt = 0;
			for(int d = 0; d < 8; ++d) {
				const int nx = x + dx[d];
				const int ny = y + dy[d];

				if(!out(nx, ny, n) && state[ny][nx] != '.') ++cnt;
			}

			if(cnt == 3 || (cnt == 2 && state[y][x] == '#')) {
				res[y][x] = '#';
			}
		}
	}

	return res;
}

int bfs(const vector<string> &start) {
	const int n = start.size();
	const int s = encode(start);
	const int goal_mask = (1 << (n * n)) - 1;

	if((s & goal_mask) == 0) return 0;

	unordered_map<int, int> dist;
	queue<int> que;

	dist.insert({s, 0});
	que.push(s);

	while(!que.empty()) {
		const int code = que.front();
		que.pop();

		const int current_dist = dist[code];
		const auto state = decode(code, n);
		const int x = (code >> (n * n)) % n;
		const int y = (code >> (n * n)) / n;

		for(int d = 0; d < 8; ++d) {
			const int nx = x + dx[d];
			const int ny = y + dy[d];

			if(out(nx, ny, n) || state[ny][nx] == '#') continue;

			vector<string> next_state(state);
			swap(next_state[ny][nx], next_state[y][x]);
			next_state = update(move(next_state));
			const int next_code = encode(next_state);

			if(!dist.count(next_code)) {
				if((next_code & goal_mask) == 0) return current_dist + 1;
				dist.insert({next_code, current_dist + 1});
				que.push(next_code);
			}
		}
	}

	return -1;
}

int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);

	int cnt = 0;
	for(int n; cin >> n && n;) {
		vector<string> start(n);
		for(auto &e : start) cin >> e;
		cout << bfs(start) << endl;
	}

	return EXIT_SUCCESS;
}