// -*- coding:utf-8-unix -*-

use num::Float;
use proconio::input;
use std::collections::{BTreeSet, VecDeque};

// ABC086C - Traveling
// https://atcoder.jp/contests/abs/fasks/arc089_a

fn switch<T>(flag: bool, t: T, f: T) -> T {
    if flag {
        t
    } else {
        f
    }
}

fn main() {
    input! {
        n:usize,
        ps :[i32;n*n]
    }
    //create table
    let mut seats = vec![vec!(-1; n + 2); n + 2];
    seats[n + 1] = vec![-1; n + 2];
    for i in 1..n + 1 {
        for j in 1..n + 1 {
            seats[i][j] = (n * (i - 1) + (j - 1) + 1) as i32;
        }
    }

    let get_position = |seats: &Vec<Vec<i32>>, m: i32| -> Option<(usize, usize)> {
        for i in 1..=n {
            for j in 1..=n {
                if seats[i][j] == m {
                    return Some((i, j));
                }
            }
        }
        None
    };

    let mut count = 0;
    for id in ps.iter() {
        //深さ優先
        //print!("\nid={}", id);
        let mut past = BTreeSet::new();
        let mut stack = Vec::new();
        let (px, py) = get_position(&seats, *id).unwrap();
        stack.push((0i32, px, py));
        loop {
            stack.sort_by_key(|(c, _, _)| -c);
            if let Some(now) = stack.pop() {
                let (c, i, j) = now;
                //print!("({},{})-", i, j);
                if seats[i][j] == -1 {
                    count += c;
                    //println!("{}", c);
                    seats[px][py] = 0;
                    break;
                }

                if !past.contains(&(i, j + 1)) {
                    let c = switch(seats[i][j + 1] > 0, c + 1, c);
                    stack.push((c, i, j + 1));
                }
                if !past.contains(&(i, j - 1)) {
                    let c = switch(seats[i][j - 1] > 0, c + 1, c);
                    stack.push((c, i, j - 1));
                }

                if !past.contains(&(i + 1, j)) {
                    let c = switch(seats[i + 1][j] > 0, c + 1, c);
                    stack.push((c, i + 1, j));
                }

                if !past.contains(&(i - 1, j)) {
                    let c = switch(seats[i - 1][j] > 0, c + 1, c);
                    stack.push((c, i - 1, j));
                }
                past.insert((i, j));
            }
        }
    }

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