use proconio::{fastout, input};

use proconio::marker::Usize1;
use std::cmp::min;

#[fastout]
fn main() {
    let abs = |x, y| if x > y { x - y } else { y - x };
    input! {
        n: usize,
        p: [Usize1; n * n],
    }
    let mut uf = UnionFind::new(n * n);
    let mut ans = 0;
    for i in 0..n * n {
        let mut c = min(
            min(p[i] / n, n - 1 - p[i] / n),
            min(p[i] % n, n - 1 - p[i] % n),
        );
        for j in 0..i {
            let d = abs(p[i] / n, p[j] / n) + abs(p[i] % n, p[j] % n);
            c = min(c, uf.cost(j) + d - 1);
            if d == 1 {
                uf.unite(i, j);
            }
        }
        uf.set_cost(i, c);
        ans += c;
    }
    println!("{}", ans);
}

#[allow(dead_code)]
struct UnionFind {
    par: Vec<usize>,
    size: Vec<usize>,
    cost: Vec<usize>,
}
impl UnionFind {
    #[allow(dead_code)]
    fn new(n: usize) -> Self {
        UnionFind {
            par: (0..n).collect(),
            size: vec![1; n],
            cost: vec![std::usize::MAX; n],
        }
    }
    #[allow(dead_code)]
    fn find(&mut self, x: usize) -> usize {
        if self.par[x] == x {
            x
        } else {
            let p = self.find(self.par[x]);
            self.par[x] = p;
            p
        }
    }
    #[allow(dead_code)]
    fn unite(&mut self, x: usize, y: usize) {
        let x = self.find(x);
        let y = self.find(y);
        if x == y {
            return;
        }
        if self.size[x] < self.size[y] {
            self.par[x] = y;
            self.size[y] += self.size[x];
            self.cost[y] = min(self.cost[y], self.cost[x]);
        } else {
            self.par[y] = x;
            self.size[x] += self.size[y];
            self.cost[x] = min(self.cost[x], self.cost[y]);
        }
    }
    #[allow(dead_code)]
    fn same(&mut self, x: usize, y: usize) -> bool {
        self.find(x) == self.find(y)
    }
    #[allow(dead_code)]
    fn size(&mut self, x: usize) -> usize {
        let x = self.find(x);
        self.size[x]
    }
    #[allow(dead_code)]
    fn cost(&mut self, x: usize) -> usize {
        let x = self.find(x);
        self.cost[x]
    }
    #[allow(dead_code)]
    fn set_cost(&mut self, x: usize, cost: usize) {
        let x = self.find(x);
        self.cost[x] = cost;
    }
}
