require 'set'

def change_state(n, state)
    new_state = 0
    (0..n-1).each do |i|
        (0..n-1).each do |j|
            count = 0
            t = (i == 0 ? 0 : i-1)
            b = (i == n-1 ? n-1 : i+1)
            l = (j == 0 ? 0 : j-1)
            r = (j == n-1 ? n-1 : j+1)
            (t..b).each do |y|
                (l..r).each do |x|
                    next if y == i && x == j
                    count += 1 if state[y * n + x] == 1
                end
            end

            if state[i * n + j] == 1
                if count == 2 || count == 3
                    new_state |= (1 << i * n + j)
                end
            elsif count == 3
                new_state |= (1 << i * n + j)
            end
        end
    end
    new_state
end

loop do
    n = gets.to_i
    break if n == 0

    inf_state = 0
    x = y = nil
    n.times do |i|
        gets.chomp.each_char.with_index do |c, j|
            if c == ?#
                inf_state |= (1 << i * n + j)
            elsif c == ?@
                y = i
                x = j
            end
        end
    end

    if inf_state == 0
        puts 0
        next
    end

    state = (inf_state << 6) + (x << 3) + y
    queue = [state]
    reached = Set[state]
    d = 1

    catch(:break) do
        until queue.empty?
            new_queue = []
            until queue.empty?
                state = queue.shift
                inf_state, x0, y0 = state >> 6, (state >> 3) & 7, state & 7
                [-1, 0, 1].repeated_permutation(2) do |dx, dy|
                    next if dx == 0 && dy == 0
                    x, y = x0 + dx, y0 + dy
                    next if x < 0 || x >= n || y < 0 || y >= n
                    next if inf_state[y * n + x] == 1

                    k = y * n + x
                    changed = change_state(n, inf_state + (1 << k))
                    changed -= (1 << k) if changed[k] == 1

                    if changed == 0
                        throw :break
                    end

                    new_state = (changed << 6) + (x << 3) + y
                    next if reached.include?(new_state)
                    reached << new_state
                    new_queue << new_state
                end
            end
            queue = new_queue
            d += 1
        end
        d = -1
    end

    p d
end