Read problems statements in Mandarin and Russian. Translations in Vietnamese to be uploaded soon. 

You have a matrix of size N * N with rows numbered through 1 to N from top to bottom and columns through 1 to N from left to right. It contains all values from 1 to N^{2}, i.e. each value from 1 to N^{2} occurs exactly once in the matrix.

Now, you start from the cell containing value 1, and from there visit the cell with value 2, and then from there visit the cell with value 3, and so on till you have visited cell containing the number N^{2}. In a single step, you can move from a cell to one of its adjacent cells. Two cells are said to be adjacent to each other if they share an edge between them.

Find out minimum number of steps required.

For example, if matrix is 

1 3
2 4
 
You start from cell containing value 1 (i.e. (1,1)) and you want to visit cell with value 2 (i.e. (2,1)). Now, from cell (2,1) you have to visit cell (1,2), which can be done is 2 steps (First we go from (2, 1) to (1, 1) and then to (1, 2), total 2 steps). Finally you move to cell where value 4 is present in 1 step. So, total number of steps required is 4.

------ Input ------ 

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the size of matrix. Each of the next N lines contain N integers denoting the values in the rows of the matrix.

------ Output ------ 

For each test case, output in a single line the required answer.

------ Constraints ------ 

$1 ≤ T ≤ 5$
$1 ≤ N ≤ 500$

------ Subtasks ------ 

$ Subtask 1 (30 points) : 1 ≤ N ≤ 20$
$ Subtask 2 (70 points) : Original constraints$

----- Sample Input 1 ------ 
2
2
1 3
2 4
3
1 7 9
2 4 8
3 6 5
----- Sample Output 1 ------ 
4
12
----- explanation 1 ------ 
Example case 1. Explained in the statement.

Example case 2.
This is the sequence of cells visited: 
(1,1) to (2,1) to (3,1) to (2,2) to (3,3) to (3,2) to (1,2) to (2,3) to (1,3).

Warning: Large input files, use scanf instead of cin in C/C++.

Difficulty: EASY

Starter code:

Solutions:
t = int(input())
for i in range(t):
	n = int(input())
	l = [(-1, -1) for j in range(n ** 2)]
	for j in range(n):
		temp = [int(k) for k in input().split()]
		for k in range(n):
			l[temp[k] - 1] = (j, k)
	ans = 0
	for j in range(n ** 2 - 1):
		ans += abs(l[j + 1][0] - l[j][0]) + abs(l[j + 1][1] - l[j][1])
	print(ans)


ujju = int(input())
for jyo in range(ujju):
	sur = int(input())
	pro = {}
	esh = []
	for p in range(sur):
		esh.append([int(pp) for pp in input().split()])
		for l in range(sur):
			pro[esh[p][l]] = [p, l]
	tro = 0
	for yp in range(2, sur * sur + 1):
		tro += abs(pro[yp - 1][0] - pro[yp][0]) + abs(pro[yp - 1][1] - pro[yp][1])
	print(tro)


def main():
	testCases = int(input())
	while testCases:
		numOfRow = int(input())
		mainList = [[0, 0] for i in range(0, numOfRow * numOfRow)]
		for rowInd in range(0, numOfRow):
			colList = [int(x) for x in input().split()]
			for colInd in range(0, numOfRow):
				mainList[colList[colInd] - 1] = [rowInd, colInd]
		numOfSteps = 0
		currentInd = mainList[0]
		for element in mainList[1:]:
			numOfSteps += abs(currentInd[0] - element[0]) + abs(currentInd[1] - element[1])
			currentInd = element
		print(numOfSteps)
		testCases -= 1
main()


for _ in range(int(input())):
	n = int(input())
	matrix = []
	for _ in range(n):
		matrix.append(list(map(int, input().split())))
	pos = {}
	for i in range(n):
		for j in range(n):
			pos[matrix[i][j]] = [i + 1, j + 1]
	pos = dict(sorted(pos.items(), key=lambda x: x[0]))
	ans = 0
	for i in range(1, len(pos)):
		a = abs(pos[i + 1][0] - pos[i][0]) + abs(pos[i + 1][1] - pos[i][1])
		ans += a
	print(ans)


t = int(input())
for x in range(t):
	n = int(input())
	s = {}
	l = []
	for i in range(n):
		l.append([int(o) for o in input().split()])
		for y in range(n):
			s[l[i][y]] = [i, y]
	c = 0
	for m in range(2, n * n + 1):
		c += abs(s[m - 1][0] - s[m][0]) + abs(s[m - 1][1] - s[m][1])
	print(c)


from collections import defaultdict
t = int(input())
while t > 0:
	d = defaultdict()
	n = int(input())
	i = 0
	while i < n:
		a = [int(x) for x in input().split()]
		for j in range(len(a)):
			d[a[j]] = [i, j]
		i = i + 1
	c = 0
	for i in range(1, n * n):
		c = c + abs(d[i + 1][0] - d[i][0]) + abs(d[i + 1][1] - d[i][1])
	print(c)
	t = t - 1


for _ in range(int(input())):
	N = int(input())
	A = []
	for i in range(N):
		B = list(map(int, input().split()))
		for (j, b) in enumerate(B):
			A.append((b, i, j))
	A.sort(key=lambda x: x[0])
	steps = 0
	for (a, i, j) in A:
		if a > 1:
			steps += abs(i - pi) + abs(j - pj)
		pi = i
		pj = j
	print(steps)


def m(arr):
	l = []
	l1 = []
	d = dict()
	h = dict()
	l1 = []
	s = 0
	l = []
	for i in range(len(arr)):
		for j in range(len(arr)):
			d[arr[i][j]] = i
			h[arr[i][j]] = j
	for i in range(1, n * n + 1):
		l.append(d[i])
		l1.append(h[i])
	for i in range(len(l) - 1):
		s += abs(l1[i] - l1[i + 1]) + abs(l[i] - l[i + 1])
	print(s)
t = int(input())
for i in range(t):
	n = int(input())
	arr = []
	for i in range(n):
		b = list((int(x) for x in input().split()))
		arr.append(b)
	m(arr)


for T in range(int(input())):
	N = int(input())
	mat_map = {}
	matrix = []
	steps = 0
	for row in range(N):
		matrix.append(list(map(int, input().split())))
		for col in range(N):
			mat_map[matrix[row][col]] = [row, col]
	for position in range(2, N ** 2 + 1):
		steps += abs(mat_map[position - 1][0] - mat_map[position][0]) + abs(mat_map[position - 1][1] - mat_map[position][1])
	print(steps)


for o in range(int(input())):
	n = int(input())
	m = []
	for h in range(n):
		m.append([int(l) for l in input().split()])
	d = {}
	for i in range(n):
		for j in range(n):
			d[m[i][j]] = (i, j)
	s = 0
	for k in range(2, n * n + 1):
		s += abs(d[k][0] - d[k - 1][0]) + abs(d[k][1] - d[k - 1][1])
	print(s)


t = input()
for c in range(0, int(t)):
	size = int(input())
	if size == 1:
		element = input()
		print(0)
		continue
	element_dict = {}
	for j in range(size):
		arr = list(map(int, input().split()))
		for k in range(size):
			element_dict[arr[k]] = [j, k]
	last_ele = size * size + 1
	ans = 0
	for j in range(2, last_ele):
		ans += abs(element_dict[j - 1][0] - element_dict[j][0])
		ans += abs(element_dict[j - 1][1] - element_dict[j][1])
	print(ans)


try:

	def manhattan(a, b):
		return abs(a[0] - b[0]) + abs(a[1] - b[1])
	for _ in range(int(input())):
		lst = []
		n = int(input())
		for _ in range(n):
			lst.append(list(map(int, input().split())))
		d = {}
		res = 0
		for i in range(len(lst)):
			for j in range(len(lst[i])):
				d[lst[i][j]] = [i, j]
		for i in range(1, n * n):
			res += manhattan(d[i], d[i + 1])
		print(res)
except EOFError:
	pass


def path(n, z):
	sum = 0
	for i in range(2, n * n + 1):
		sum = sum + abs(z[i][0] - z[i - 1][0]) + abs(z[i][1] - z[i - 1][1])
	return sum
test_case = int(input())
for t in range(test_case):
	n = int(input())
	z = [[0 for x in range(2)] for x in range(n * n + 1)]
	for m in range(n):
		inp = [int(x) for x in input().split()]
		for k in range(n):
			z[inp[k]][0] = m + 1
			z[inp[k]][1] = k + 1
	print(path(n, z))


def find(obj, array, size):
	out = []
	for x in range(size):
		for y in range(size):
			if array[x][y] == obj:
				return [x, y]
res = []
for _ in range(int(input())):
	n = int(input())
	look = {}
	step = 0
	for i in range(n):
		row = list(map(int, input().split()))
		for j in range(n):
			look[row[j]] = [i, j]
	co = look[1]
	for i in range(2, n * n + 1):
		nex = look[i]
		step = step + abs(co[0] - nex[0]) + abs(co[1] - nex[1])
		co = nex
	res.append(step)
for i in res:
	print(i)


for _ in range(int(input())):
	n = int(input())
	m = []
	dick = {}
	c = 0
	for i in range(n):
		l = list(map(int, input().split()))
		m.append(l)
		for j in range(n):
			dick[m[i][j]] = [i, j]
	for k in range(2, n * n + 1):
		c += abs(dick[k - 1][0] - dick[k][0]) + abs(dick[k - 1][1] - dick[k][1])
	print(c)


T = int(input())
for test_case_index in range(T):
	N = int(input())
	rows = [None] * (N * N)
	columns = [None] * (N * N)
	for row_index in range(N):
		row = [int(number) for number in input().split()]
		for (column_index, number) in enumerate(row):
			rows[number - 1] = row_index + 1
			columns[number - 1] = column_index + 1
	result = 0
	previous_number = 1
	current_number = 2
	while current_number <= N * N:
		dist_y = abs(rows[current_number - 1] - rows[previous_number - 1])
		dist_x = abs(columns[current_number - 1] - columns[previous_number - 1])
		result += dist_y + dist_x
		previous_number = current_number
		current_number += 1
	print(result)


for _ in range(int(input())):
	n = int(input())
	d = {}
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(n):
			d[a[j]] = [i, j]
	ans = 0
	for i in range(2, n * n + 1):
		a = d[i - 1]
		b = d[i]
		ans += abs(a[0] - b[0]) + abs(a[1] - b[1])
	print(ans)


n = int(input())
for _ in range(n):
	size = int(input())
	matrix = []
	for i in range(size):
		matrix.append(list(map(int, input().split(' ', size - 1))))
	nums = size ** 2
	xx = 0
	yy = 0
	sum = 0
	d = {}
	for i in range(size):
		for j in range(size):
			d[matrix[i][j]] = (i, j)
	(x1, y1) = d[1]
	for k in range(2, size * size + 1):
		(x2, y2) = d[k]
		sum += abs(x2 - x1) + abs(y2 - y1)
		x1 = x2
		y1 = y2
	print(sum)


T = int(input())
while T:
	T -= 1
	N = int(input())
	matrix = []
	for n in range(N):
		matrix += (int(x) for x in input().split())
	sortedindex = sorted(range(len(matrix)), key=lambda k: matrix[k])
	prevpos = sortedindex[0]
	steps = 0
	for i in range(1, len(sortedindex)):
		nextpos = sortedindex[i]
		steps += abs(nextpos // N - prevpos // N)
		steps += abs(nextpos % N - prevpos % N)
		prevpos = nextpos
	print(steps)


for t in range(int(input())):
	n = int(input())
	d = {}
	a = 0
	for i in range(n):
		m = list(map(int, input().split()))
		for i in range(n):
			d[m[i]] = (a // n + 1, a % n + 1)
			a = a + 1
	c = 1
	ans = 0
	(px, py) = d[1]
	for i in range(1, n * n + 1):
		(x, y) = d[c]
		ans = ans + abs(px - x) + abs(py - y)
		px = x
		py = y
		c = c + 1
	print(ans)


import sys
tc = int(input())
while tc:
	tc -= 1
	n = int(input())
	d = {}
	for i in range(n):
		dd = list(map(int, sys.stdin.readline().strip().split()))
		for j in range(n):
			d[dd[j]] = [i, j]
	sum_ = 0
	for i in range(2, n * n + 1):
		sum_ += abs(d[i][0] - d[i - 1][0]) + abs(d[i][1] - d[i - 1][1])
	print(sum_)


test_cases = int(input())
for _ in range(test_cases):
	dimension = int(input())
	sequence = [None] * dimension ** 2
	for row in range(dimension):
		numbers = list(map(int, input().split()))
		for column in range(len(numbers)):
			number = numbers[column]
			sequence[number - 1] = (row, column)
	cost = 0
	for step_index in range(len(sequence) - 1):
		this_step = sequence[step_index]
		next_step = sequence[step_index + 1]
		cost += abs(this_step[0] - next_step[0])
		cost += abs(this_step[1] - next_step[1])
	print(cost)


def mat(n):
	steps = 0
	l1 = [None] * n ** 2
	l2 = [None] * n ** 2
	a = [[]] * n
	for i in range(n):
		a[i] = list(map(int, input().split()))
		for j in range(n):
			l1[a[i][j] - 1] = i
			l2[a[i][j] - 1] = j
	for i in range(0, len(l1) - 1):
		steps = steps + abs(l1[i] - l1[i + 1]) + abs(l2[i] - l2[i + 1])
	return steps
t = int(input())
fin = [None] * t
for i in range(0, t):
	n = int(input())
	fin[i] = mat(n)
for i in range(0, len(fin)):
	print(fin[i])


case = int(input())
for i in range(case):
	n = int(input())
	l = [[0 for x in range(n)] for x in range(n)]
	count = 0
	for x in range(n):
		l1 = list(input().split())
		for y in range(n):
			l[x][y] = int(l1[y])
	d = {}
	for x in range(n):
		for y in range(n):
			d[l[x][y]] = [x, y]
	for z in range(2, n * n + 1):
		count += abs(d[z][0] - d[z - 1][0]) + abs(d[z][1] - d[z - 1][1])
	print(count)


t = int(input())
g = 0
while g < t:
	g = g + 1
	k = int(input())
	j = 0
	size = k * k
	arr = [None] * size
	for i in range(size):
		arr[i] = [None] * 2
	while j < k:
		z = 0
		string = input()
		string = string.split(' ')
		for n in string:
			arr[int(n) - 1][0] = j
			arr[int(n) - 1][1] = z
			z = z + 1
		j = j + 1
	j = 0
	x = arr[0][0]
	y = arr[0][1]
	SUM = 0
	while j < size:
		SUM = SUM + abs(x - arr[j][0]) + abs(y - arr[j][1])
		x = arr[j][0]
		y = arr[j][1]
		j = j + 1
	print(SUM)


def check(z):
	st = 0
	n = len(z)
	for i in range(n - 1):
		r = abs(z[i][1] - z[i + 1][1]) + abs(z[i][2] - z[i + 1][2])
		st = st + r
	print(st)
t = int(input())
for i in range(t):
	n = int(input())
	a = []
	z = []
	for i in range(n):
		b = list(map(int, input().strip().split()))
		for j in range(n):
			c = []
			c.append(b[j])
			c.append(i)
			c.append(j)
			z.append(c)
		a.append(b)
	z.sort()
	check(z)


t = int(input())
for j in range(t):
	n = int(input())
	b = [[0 for x in range(2)] for x in range(n * n + 1)]
	for i in range(n):
		m = input()
		m = m.split()
		for k in range(len(m)):
			b[int(m[k])][0] = i + 1
			b[int(m[k])][1] = k + 1
	count = 0
	for j in range(1, n * n):
		count = count + abs(b[j][0] - b[j + 1][0]) + abs(b[j][1] - b[j + 1][1])
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = []
	for i in range(n):
		b = list(map(int, input().split()))
		for (j, d) in enumerate(b):
			a.append((d, i, j))
	a.sort()
	steps = 0
	for (y, i, j) in a:
		if y > 1:
			steps += abs(i - pi) + abs(j - pj)
		pi = i
		pj = j
	print(steps)


for t in range(int(input())):
	n = int(input())
	plm = {}
	for i in range(n):
		x = [int(i) for i in input().split()]
		for j in range(n):
			plm[x[j]] = [i, j]
	plm = [v for (k, v) in sorted(plm.items())]
	count = 0
	for i in range(1, n ** 2):
		count += abs(plm[i][0] - plm[i - 1][0]) + abs(plm[i][1] - plm[i - 1][1])
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	mat = []
	for _ in range(n):
		a = list(map(int, input().strip().split(' ')))
		t = []
		for i in range(n):
			t.append(a[i])
		mat.append(t)
	cost = 0
	myDict = {}
	for i in range(n):
		for j in range(n):
			myDict[mat[i][j]] = [i, j]
	for i in range(1, n * n, 1):
		t1 = myDict[i]
		t2 = myDict[i + 1]
		cost = cost + abs(t1[0] - t2[0]) + abs(t1[1] - t2[1])
	print(cost)


try:
	t = input()
except EOFError:
	t = 0
t = int(t)
for i in range(t):
	n = int(input())
	dict = {}
	for j in range(n):
		m = input().split()
		m = [int(x) for x in m]
		for k in range(n):
			dict[m[k]] = j * n + k
	sum = 0
	for l in range(n * n - 1):
		t_1 = dict[l + 1]
		t_2 = dict[l + 2]
		j_1 = t_1 // n
		k_1 = t_1 % n
		j_2 = t_2 // n
		k_2 = t_2 % n
		sum = sum + abs(j_1 - j_2) + abs(k_1 - k_2)
	print(sum)


t = int(input())
for i in range(t):
	s = int(input())
	m = [[]] * s
	l = [None] * s * s
	for i in range(s):
		m[i] = list(map(int, input().split()))
		for j in range(s):
			l[m[i][j] - 1] = (i, j)
	steps = 0
	for i in range(s * s - 1):
		steps += sum((abs(l[i][k] - l[i + 1][k]) for k in range(2)))
	print(steps)


t = int(input())
for i in range(t):
	n = int(input())
	a = [0] * (n * n)
	b = [0] * (n * n)
	for j in range(n):
		temp = list(map(int, input().split()))
		for k in range(n):
			a[temp[k] - 1] = j
			b[temp[k] - 1] = k
	ans = 0
	for j in range(n * n - 1):
		ans += abs(a[j] - a[j + 1])
		ans += abs(b[j] - b[j + 1])
	print(ans)


def take_input_matrix(n):
	matrix = []
	row_num = 0
	while row_num < n:
		input_string = str(input())
		values = input_string.split(' ')
		row = [int(value) for value in values]
		matrix.append(row)
		row_num += 1
	return matrix

def calculate_steps(matrix):
	n = len(matrix)
	row_list = [0] * n ** 2
	column_list = [0] * n ** 2
	for row_num in range(0, n):
		for column_num in range(0, n):
			row_list[matrix[row_num][column_num] - 1] = row_num
			column_list[matrix[row_num][column_num] - 1] = column_num
	steps = 0
	for index in range(1, n ** 2):
		steps += abs(row_list[index] - row_list[index - 1]) + abs(column_list[index] - column_list[index - 1])
	return steps
num_of_cases = int(input())
while 6 > num_of_cases > 0:
	n = int(input())
	if 0 < n < 501:
		matrix = take_input_matrix(n)
	else:
		break
	steps = calculate_steps(matrix)
	num_of_cases -= 1
	print(steps)


for t in range(int(input())):
	row_num = int(input())
	coordinates = [None] * (row_num * row_num)
	for y in range(row_num):
		rows = list(map(int, input().split()))
		for (x, val) in enumerate(rows):
			coordinates[val - 1] = (x, y)
	total_steps = 0
	for i in range(1, len(coordinates)):
		(x1, y1) = (coordinates[i - 1][0], coordinates[i - 1][1])
		(x2, y2) = (coordinates[i][0], coordinates[i][1])
		step = abs(x1 - x2) + abs(y1 - y2)
		total_steps += step
	print(total_steps)


t = int(input())
for _ in range(t):
	n = int(input())
	d = {}
	for i in range(n):
		row = [int(x) for x in input().split()]
		for (j, val) in enumerate(row):
			d[val] = (i, j)
	distance = 0
	curr_val = 1
	next_val = 2
	while next_val in d:
		diff_x = abs(d[next_val][0] - d[curr_val][0])
		diff_y = abs(d[next_val][1] - d[curr_val][1])
		distance += diff_x + diff_y
		curr_val += 1
		next_val += 1
	print(distance)


import sys

def dist(xy1, xy2):
	return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])

def ans():
	for _ in range(int(sys.stdin.readline())):
		n = int(sys.stdin.readline())
		d = {}
		for y in range(n):
			xcoor = list(map(int, sys.stdin.readline().split()))
			for x in range(len(xcoor)):
				d[xcoor[x]] = (x, y)
		a = 0
		for i in range(2, n ** 2 + 1):
			a += dist(d[i], d[i - 1])
		yield a
for i in ans():
	print(i)


t = int(input())
for _ in range(t):
	size = int(input())
	matrix = []
	for i in range(size):
		matrix.append(list(map(int, input().split())))
	position = {}
	for r in range(size):
		for c in range(size):
			position[matrix[r][c]] = [r, c]
	d = 0
	for row in range(1, size * size):
		d += abs(position[row][0] - position[row + 1][0]) + abs(position[row][1] - position[row + 1][1])
	print(d)


class Entry:

	def __init__(self, row, column):
		self.row = row
		self.column = column
T = int(input())
for test_case_index in range(T):
	N = int(input())
	numbers = [None] * (N * N)
	for row_index in range(N):
		row = [int(number) for number in input().split()]
		for (column_index, number) in enumerate(row):
			numbers[number - 1] = Entry(row_index + 1, column_index)
	result = 0
	current_number = 1
	previous_entry = numbers[current_number - 1]
	current_number += 1
	while current_number <= N * N:
		current_entry = numbers[current_number - 1]
		dist_y = abs(current_entry.row - previous_entry.row)
		dist_x = abs(current_entry.column - previous_entry.column)
		result += dist_y + dist_x
		previous_entry = current_entry
		current_number += 1
	print(result)


t = int(input())

def calc_d(a, b):
	return abs(a[0] - b[0]) + abs(a[1] - b[1])
for i in range(t):
	n = int(input())
	mat = [[0 for i in range(n)] for j in range(n)]
	d = [(0, 0) for i in range(n * n + 1)]
	for m in range(n):
		mat[m] = list(map(int, input().split()))
	for m in range(n):
		for k in range(n):
			d[mat[m][k]] = (m, k)
	distance = 0
	for i in range(2, n * n + 1):
		distance += calc_d(d[i], d[i - 1])
	print(distance)


for t in range(int(input())):
	n = int(input())
	a = {}
	for i in range(n):
		s = list(map(int, input().split(' ')))
		for j in range(1, n + 1):
			a[s[j - 1]] = (i + 1, j)
	(x, y) = a[1]
	ans = 0
	for i in range(2, n * n + 1):
		t = abs(a[i][0] - x) + abs(a[i][1] - y)
		ans += t
		(x, y) = a[i]
	print(ans)


import sys

def min_step_from_to(i, j, x, y):
	res = abs(i - x) + abs(j - y)
	return res

def min_count():
	result = 0
	current = mat_map[0]
	for i in range(1, N ** 2):
		next = mat_map[i]
		result += min_step_from_to(current[0], current[1], next[0], next[1])
		current = next
	print(result)
	return

def main():
	T = int(sys.stdin.readline())
	t = 0
	while t < T:
		t += 1
		global N
		N = int(sys.stdin.readline())
		global mat_map
		mat_map = N ** 2 * [0]
		n = 0
		while n < N:
			line = sys.stdin.readline()
			line = line.split(' ')
			line = [int(i) for i in line]
			for i in range(0, N):
				mat_map[line[i] - 1] = (n, i)
			n += 1
		min_count()
main()


from collections import defaultdict
import inspect, os
s = inspect.getfile(inspect.currentframe())
r = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
t = int(input())
while t > 0:
	d = defaultdict()
	n = int(input())
	i = 0
	while i < n:
		a = [int(x) for x in input().split()]
		for j in range(len(a)):
			d[a[j]] = [i, j]
		i = i + 1
	c = 0
	for i in range(1, n * n):
		c = c + abs(d[i + 1][0] - d[i][0]) + abs(d[i + 1][1] - d[i][1])
	print(c)
	t = t - 1


for _ in range(int(input())):
	n = int(input())
	pos = [0] * (n ** 2 + 1)
	for y in range(n):
		l = list(map(int, input().split()))
		for x in range(n):
			pos[l[x]] = (x, y)
	total = 0
	for i in range(2, len(pos)):
		dx = abs(pos[i][0] - pos[i - 1][0])
		dy = abs(pos[i][1] - pos[i - 1][1])
		total += dx + dy
	print(total)


import sys
import math

def main():
	T = int(input())
	result = []
	for t in range(T):
		N = int(input())
		mat = dict()
		for i in range(N):
			row = input().split()
			for j in range(N):
				mat[int(row[j])] = [i, j]
		cost = 0
		for i in range(2, pow(N, 2) + 1):
			cost += math.fabs(mat[i][0] - mat[i - 1][0]) + math.fabs(mat[i][1] - mat[i - 1][1])
		result.append(math.ceil(cost))
	for t in range(T):
		print(result[t])
main()


t = int(input())
for i in range(t):
	h = int(input())
	mat = []
	for j in range(h):
		mat.append(list(map(int, input().split())))
	p = {}
	for c in range(h):
		for g in range(h):
			p[mat[c][g]] = [c, g]
	d = 0
	for row in range(1, h * h):
		d += abs(p[row][0] - p[row + 1][0]) + abs(p[row][1] - p[row + 1][1])
	print(d)


t = int(input())
for i in range(t):
	n = int(input())
	mat = []
	for j in range(n):
		row = [int(x) for x in input().split()]
		mat.append(row)
	xval = [0 for x in range(n * n)]
	yval = [0 for x in range(n * n)]
	for a in range(n):
		for b in range(n):
			xval[mat[a][b] - 1] = a
			yval[mat[a][b] - 1] = b
	res = 0
	for a in range(1, n * n):
		res += abs(xval[a - 1] - xval[a]) + abs(yval[a - 1] - yval[a])
	print(res)


tc = int(input())
for i in range(tc):
	n = int(input())
	mat = [[0 for x in range(n)] for x in range(n)]
	d = dict()
	for j in range(n):
		mat[j] = input().split()
		for k in range(n):
			d[mat[j][k]] = [j + 1, k + 1]
	count = 0
	srcCoordinates = d['1']
	for i in range(2, n * n + 1):
		destCoordinates = d[str(i)]
		count += abs(destCoordinates[0] - srcCoordinates[0]) + abs(destCoordinates[1] - srcCoordinates[1])
		srcCoordinates = destCoordinates
	print(count)


def count_steps(pointA, pointB):
	(xA, yA) = pointA
	(xB, yB) = pointB
	return abs(xA - xB) + abs(yA - yB)
t = int(input())
for case in range(t):
	matrix = dict()
	lines = int(input())
	for line in range(lines):
		m_line = map(int, input().split())
		for element in enumerate(m_line):
			matrix[element[1]] = (line + 1, element[0] + 1)
	points = list(matrix.values())
	steps = 0
	for index in range(lines * lines - 1):
		steps += count_steps(points[index], points[index + 1])
	print(steps)


for _ in range(int(input())):
	n = int(input())
	d = {}
	a = []
	for i in range(n):
		a.append([int(x) for x in input().split()])
		for j in range(n):
			d[a[i][j]] = [i, j]
	c = 0
	for i in range(2, n * n + 1):
		c += abs(d[i - 1][0] - d[i][0]) + abs(d[i - 1][1] - d[i][1])
	print(c)


import sys
t = int(input())
for i in range(0, t):
	list = []
	z = int(input())
	for j in range(0, z):
		list += [int(x) for x in sys.stdin.readline().rstrip().split()]
	newlist = sorted(range(len(list)), key=lambda k: list[k])
	item = 0
	step = 0
	prev = newlist[0]
	for i in range(1, len(newlist)):
		next = newlist[i]
		step += abs(next // z - prev // z)
		step += abs(next % z - prev % z)
		prev = next
	print(step)


for _ in range(int(input())):
	n = int(input())
	l = []
	mp = {i: [] for i in range(1, n * n + 1)}
	for i in range(n):
		l1 = list(map(int, input().split()))
		l.append(l1)
		for j in range(n):
			mp[l1[j]] = [i, j]
	ans = 0
	for i in range(2, n * n + 1):
		ans += abs(mp[i][0] - mp[i - 1][0]) + abs(mp[i][1] - mp[i - 1][1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	dict = {}
	for i in range(n):
		r = list(map(int, input().split()))
		for j in range(0, len(r)):
			dict[r[j]] = [i + 1, j + 1]
	sum = 0
	for i in range(1, n * n):
		sum1 = abs(dict[i][0] - dict[i + 1][0])
		sum2 = abs(dict[i][1] - dict[i + 1][1])
		sum += sum1 + sum2
	print(sum)


mode = 'fileee'
if mode == 'file':
	f = open('test.txt', 'r')

def fun(u, v):
	[x, y] = [int(x) for x in u]
	[p, q] = [int(x) for x in v]
	if p == x:
		return int(abs(q - y))
	if q == y:
		return int(abs(x - p))
	return abs(p - x) + abs(q - y)
d = {}
a = []
if mode == 'file':
	T = int(f.readline())
else:
	T = int(input())
for z in range(T):
	if mode == 'file':
		n = int(f.readline())
	else:
		n = int(input())
	for i in range(n):
		if mode == 'file':
			kk = [int(x) for x in f.readline().split()]
		else:
			kk = [int(x) for x in input().split()]
		for j in range(n):
			d[kk[j]] = [i, j]
	s = 0
	for i in range(1, n ** 2):
		s += fun(d[i], d[i + 1])
	print(s)
if mode == 'file':
	f.close()


num_cases = int(input())
for _ in range(num_cases):
	matrix_width = int(input())
	pos_dict = {}
	for y in range(matrix_width):
		matrix_row = map(int, input().split())
		for (x, num) in enumerate(matrix_row):
			pos_dict[num] = (x, y)
	num_moves = 0
	current_num = 1
	(x, y) = pos_dict[current_num]
	while current_num < matrix_width * matrix_width:
		(x_next, y_next) = pos_dict[current_num + 1]
		num_moves += abs(x_next - x) + abs(y_next - y)
		current_num += 1
		(x, y) = (x_next, y_next)
	print(num_moves)


tc = int(input())
for z in range(tc):
	N = int(input())
	mapNums = []
	locList = []
	for y in range(N):
		cArr = list(map(int, input().split()))
		for x in range(len(cArr)):
			locList.append([cArr[x], y, x])
	locList.sort()
	numMoves = 0
	for w in range(len(locList) - 1):
		numMoves += abs(locList[w][1] - locList[w + 1][1]) + abs(locList[w][2] - locList[w + 1][2])
	print(numMoves)


for tc in range(int(input())):
	n = int(input())
	a = []
	oldcoord = [0, 0]
	newcoord = [0, 0]
	newdist = 0
	dist = 0
	matrix = {}
	for i in range(n):
		a.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(n):
			matrix[a[i][j]] = (i, j)
	oldcoord = matrix[1]
	for i in range(2, n ** 2 + 1):
		newcoord = matrix[i]
		newdist = abs(newcoord[0] - oldcoord[0]) + abs(newcoord[1] - oldcoord[1])
		dist += newdist
		oldcoord = newcoord
	print(dist)


for _ in range(int(input())):
	n = int(input())
	d = {}
	for i in range(1, n + 1):
		l = list(map(int, input().split()))
		for j in range(1, n + 1):
			d[l[j - 1]] = (i, j)
	res = 0
	(a, b) = d[1]
	for i in range(2, len(d) + 1):
		(p, q) = d[i]
		res += abs(a - p) + abs(b - q)
		(a, b) = (p, q)
	print(res)


def distance(p1, p2):
	return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
for _ in range(int(input())):
	n = int(input())
	record = [0] * n ** 2
	for i in range(n):
		a = [int(x) for x in input().split()]
		for j in range(n):
			record[a[j] - 1] = (j, i)
	total_walk = 0
	for i in range(1, len(record)):
		total_walk += distance(record[i - 1], record[i])
	print(total_walk)


for i in range(int(input())):
	n = int(input())
	arr = []
	for i in range(n):
		t = [int(i) for i in input().split()]
		arr.append(t)
	x = [0] * n ** 2
	y = [0] * n ** 2
	for i in range(n):
		for j in range(n):
			x[arr[i][j] - 1] = i + 1
			y[arr[i][j] - 1] = j + 1
	s = 0
	for i in range(n ** 2 - 1):
		s += abs(x[i] - x[i + 1]) + abs(y[i] - y[i + 1])
	print(s)


import sys

def work(array, N):
	r = 0
	i = 2
	while i <= N * N:
		r = r + abs(array[i][0] - array[i - 1][0]) + abs(array[i][1] - array[i - 1][1])
		i = i + 1
	print(r)

def homemade(N):
	i = 0
	liste = []
	while i <= N * N:
		line = [0, 0]
		liste.append(line)
		i = i + 1
	return liste

def main():
	T = int(input())
	testcase = 0
	while testcase < T:
		N = int(input())
		rows = 0
		array = homemade(N)
		while rows < N:
			line = list(map(int, input().split()))
			ij = 0
			while ij < N:
				value = line[ij]
				array[value][0] = rows
				array[value][1] = ij
				ij = ij + 1
			rows = rows + 1
		work(array, N)
		testcase = testcase + 1
	return 0
main()


t = int(input())
while t:
	n = int(input())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	pos = {}
	for (i, j) in enumerate(mat):
		for (k, m) in enumerate(j):
			pos[m] = (i, k)
	step = 0
	for i in range(1, len(pos)):
		(x1, y1) = pos[i]
		(x2, y2) = pos[i + 1]
		step += abs(x1 - x2) + abs(y1 - y2)
	print(step)
	t -= 1


def finddist(old, new):
	return abs(old[0] - new[0]) + abs(old[1] - new[1])
T = int(input())
for Ti in range(T):
	N = int(input())
	matrix = [None] * N ** 2
	for Ri in range(1, N + 1):
		row = input().split(' ')
		for Ci in range(1, N + 1):
			matrix[int(row[Ci - 1]) - 1] = [Ri, Ci]
	dist = 0
	oldl = matrix[0]
	for now in range(N ** 2 - 1):
		newl = matrix[now + 1]
		dist += finddist(oldl, newl)
		oldl = newl
		now += 1
	print(dist)


TC = int(input())
for _ in range(TC):
	N = int(input())
	pos = [[0, 0] for i in range(N * N)]
	for i in range(N):
		row = list(map(int, input().split()))
		for j in range(N):
			pos[row[j] - 1] = [i, j]
	ans = 0
	for i in range(1, N * N):
		ans += abs(pos[i][0] - pos[i - 1][0]) + abs(pos[i][1] - pos[i - 1][1])
	print(ans)


t = int(input())
while t != 0:
	n = int(input())
	d = dict()
	for r in range(0, n):
		l = list(map(int, input().split()))
		for p in range(0, n):
			d[l[p]] = (r, p)
	s = 0
	(i, j) = d[1]
	for k in range(1, n * n):
		(p, q) = d[k + 1]
		s += abs(p - i) + abs(q - j)
		(i, j) = (p, q)
	print(s)
	t -= 1


for t in range(int(input())):
	numOfRow = int(input())
	mainList = [[0, 0] for i in range(0, numOfRow * numOfRow)]
	for rowInd in range(0, numOfRow):
		colList = [int(x) for x in input().split()]
		for colInd in range(0, numOfRow):
			mainList[colList[colInd] - 1] = [rowInd, colInd]
	numOfSteps = 0
	currentInd = mainList[0]
	for element in mainList[1:]:
		numOfSteps += abs(currentInd[0] - element[0]) + abs(currentInd[1] - element[1])
		currentInd = element
	print(numOfSteps)