#include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<cassert>
using namespace std;

#define REP(i,a,b) for(i=a; i<b; ++i)
#define rep(i,n) REP(i,0,n)

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

inline char atc(string s,int i,int j) { return s.at(i*n+j); }

bool iseliminate(string mp) {
    int i,j;
    rep(i,mp.length()) if(mp[i] == '#') return false;
    return true;
}

pair<int,int> getPos(string mp) {
    int i,j;
    rep(i,mp.length()) if(mp[i] == '@') return make_pair(i/n,i%n);
}


string update(string &mp) {
    int i,j,k;
    string tmp = mp;

    rep(i,n) rep(j,n) {
        int adj = 0;
        if(mp.at(i*n+j) == '@') continue;
        rep(k,8) {
            if(i+dy[k] < 0 || i+dy[k] >= n) continue;
            if(j+dx[k] < 0 || j+dx[k] >= n) continue;
            if(mp.at((i+dy[k])*n+(j+dx[k])) == '#'
               || mp.at((i+dy[k])*n+(j+dx[k])) == '@') adj++;
        }
        if(mp.at(i*n+j) == '#') {
            if(adj == 2 || adj == 3) continue;
            else tmp.at(i*n+j) = '.';
            //cout<<"eliminated !!"<<endl;
        }else{
            if(adj == 3) tmp.at(i*n+j) = '#';
        }
    }
    return tmp;
}

int bfs(string bmap) {
    int i,j;
    queue<pair<int,string > >Q;
    set<string> memo;
    memo.insert(bmap);
    Q.push(make_pair(0,bmap));
    while(!Q.empty()) {
        string nmap = Q.front().second;
        int ii = Q.front().first;
        Q.pop();


        // cout<<ii<<endl;
        // rep(i,n) cout<<nmap.substr(i*n,n)<<endl;
        // cout<<endl;

        if(iseliminate(nmap)) return ii;

        pair<int,int> pos = getPos(nmap);
        for(int i=0; i<8; ++i) {
            if(pos.first+dy[i] < 0 || pos.first+dy[i] >= n) continue;
            if(pos.second+dx[i] < 0 || pos.second+dx[i] >= n) continue;
            if(nmap.at((pos.first+dy[i])*n+(pos.second+dx[i])) == '#') continue;
            string next = string(nmap);
            next.at((pos.first+dy[i])*n+pos.second+dx[i]) = '@';
            next.at((pos.first)*n+pos.second) = '.';
            next = update(next);
            if(memo.find(next) != memo.end()) continue;
            memo.insert(next);
            Q.push(make_pair(ii+1, next));
        }
    }
    return -1;
    assert(false);
}

int main() {
    while(cin>>n, n) {
        string imap = "",tmp;
        for(int i=0; i<n; ++i) {
            cin>>tmp;
            imap += tmp;
        }
        cout<<bfs(imap)<<endl;
    }
}