#include <bits/stdc++.h>
using namespace std;

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

struct state {
    int y, x, infected;
    bool operator<(state const& s) const {
        return make_tuple(y, x, infected) < make_tuple(s.y, s.x, s.infected);
    }
};

bool is_in(int y, int x, int n) {
    return (0 <= y && y < n && 0 <= x && x < n);
}

int next_infected(int y, int x, int infected, int n) {
    int res = 0;
    for(int i=0; i<n; ++i) {
        for(int j=0; j<n; ++j) {
            if(i == y && j == x) {
                continue;
            }
            int cnt = 0;
            for(int k=0; k<8; ++k) {
                int adj_y = i + dy[k];
                int adj_x = j + dx[k];
                if(!is_in(adj_y, adj_x, n)) {
                    continue;
                }
                cnt += (adj_y == y && adj_x == x) || (infected >> (adj_y * n + adj_x)) & 1;
            }
            if((infected >> (i * n + j)) & 1) {
                if(cnt == 2 || cnt == 3) {
                    res |= 1 << (i * n + j);
                }
            } else {
                if(cnt == 3) {
                    res |= 1 << (i * n + j);
                }
            }
        }
    }
    return res;
}

int main() {
    int n;
    while(cin >> n, n) {
        vector<string> v(n);
        int sy, sx, sinfected = 0;
        for(int i=0; i<n; ++i) {
            cin >> v[i];
            for(int j=0; j<n; ++j) {
                if(v[i][j] == '@') {
                    sy = i;
                    sx = j;
                } else if(v[i][j] == '#') {
                    sinfected |= 1 << (i * n + j);
                }
            }
        }
        map<state, int> memo;
        memo[state{sy, sx, sinfected}] = 0;
        queue<state> que;
        que.push(state{sy, sx, sinfected});
        int res = INF;
        while(!que.empty()) {
            auto now = que.front();
            que.pop();
            if(now.infected == 0) {
                res = memo[now];
                break;
            }
            for(int i=0; i<8; ++i) {
                int ny = now.y + dy[i];
                int nx = now.x + dx[i];
                if(!is_in(ny, nx, n) || (now.infected >> (ny * n + nx)) & 1) {
                    continue;
                }
                int next_inf = next_infected(ny, nx, now.infected, n);
                auto next = state{ny, nx, next_inf};
                if(memo.count(next) == 0) {
                    memo[next] = memo[now] + 1;
                    que.push(next);
                }
            }
        }
        cout << (res == INF ? -1 : res) << endl;
    }
}
