#include <iostream>

using namespace std;

int t,h,l;
int a[51][51];
int kon[51];
int coo[2800][2];

int ab(int a)
{
	if (a < 0)
		return -a;
	return a;
}

int main()
{
	freopen("TOWER.IN","r",stdin);
	//freopen("output.txt","w",stdout);
	cin >> t;
	for (int ii=0;ii<t;ii++)
	{
		int car = 0;
		cin >> h >> l;
		for (int j=0;j<h;j++)
		{
			for (int k=0;k<l;k++)
			{
				cin >> a[j][k];
				if (a[j][k] > car)
					car = a[j][k];
				if (a[j][k] > 0)
				{
					coo[a[j][k]][0] = j;
					coo[a[j][k]][1] =k;
				}
			}
			kon[j] = 0;
		}
		int time = 0;
		for (int i=1;i<=car;i++)
		{
			time += coo[i][0] * 20;
			int a = kon[coo[i][0]];
			int b = coo[i][1];

			int res1 = ab(b-a);
			int res2 = ab(l - ab(b-a));
			if (res1 < res2)
				time += res1 * 5;
			else
				time += res2 * 5;
			kon[coo[i][0]] = b;
			//cout << "time =" << time << " " << a << "," << b << endl;
		}
		cout << time << endl;
	}

	return 0;
}