#![allow(unused)]

use proconio::input;
use proconio::marker::{Bytes, Chars, Usize1};
use std::cmp::{max, min};

#[proconio::fastout]
fn main() {
    input! {
        n: usize,
        ps: [Usize1; n * n],
    }

    let seat = |i, j| i * n + j;

    let mut g: Vec<Vec<usize>> = vec![vec![]; n * n];
    let exit = std::usize::MAX;

    for i in 0..n {
        g[seat(i, 0)].push(exit);
        g[seat(i, n - 1)].push(exit);
    }
    for j in 1..(n - 1) {
        g[seat(0, j)].push(exit);
        g[seat(n - 1, j)].push(exit);
    }

    for i in 1..(n - 1) {
        for j in 1..(n - 1) {
            let adjs = [
                seat(i - 1, j),
                seat(i + 1, j),
                seat(i, j - 1),
                seat(i, j + 1)
            ];
            g[seat(i, j)].extend(adjs.iter());
        }
    }

    let mut exited = vec![false; n * n];
    let mut costs = vec![0; n * n];
    for i in 0..n {
        for j in 0..n {
            costs[seat(i, j)] =
                *[i, j, n - 1 - i, n - 1 - j].iter().min().unwrap();
        }
    }

    let mut ans = 0;
    for p in ps {
        exited[p] = true;
        let cost = if costs[p] == 0 {
            0
        } else {
            let mut added = vec![false; n * n];
            let mut newadjs = vec![];
            let mut hasexit = false;
            std::mem::swap(&mut g[p], &mut newadjs);
            while let Some(s) = newadjs.pop() {
                if s == exit {
                    hasexit = true;
                } else if exited[s] {
                    newadjs.extend(g[s].iter());
                } else {
                    if !added[s] {
                        g[p].push(s);
                        added[s] = true;
                    }
                }
            }

            g[p].sort_unstable();
            g[p].dedup();

            if hasexit {
                g[p].push(exit);
                0
            } else {
                g[p].iter().map(|&s| costs[s]).min().unwrap() + 1
            }
        };

        ans += cost;
    }

    println!("{}", ans);
}
