#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

int main()
{
	ifstream in("TOWER.IN");
	int t;
	in>>t;
	for (int i=0;i<t;i++)
	{
		int h,l;
		in>>h>>l;
		vector<int> car(h*l,-1);
		vector<vector<int> > tower(h,vector<int>(l,0));
		for (int q=0;q<h;q++)
		{
			for (int j=0;j<l;j++)
			{
				in>>tower[q][j];
				if (tower[q][j]!=-1) car[tower[q][j]-1]=q;
			}
		}
		__int64 r=0;
		vector<int> con(h,0);
		for (int j=0;j<h*l;j++)
		{
			if (car[j]==-1) continue;
			r+=(car[j])*20;
			for (int b=0;b<l;b++) 
			{
				if (tower[car[j]][b]==j+1)
				{
					int z1,z2;
					z1=abs(con[car[j]]-b);
					z2=abs(l-abs(con[car[j]]-b));
					if (z1<z2)r+=z1*5;
					else r+=z2*5;
					con[car[j]]=b;
				}
			}
		}
		cout<<r<<endl;
	}
	return 0;
}