# include <iostream>
# include <vector>
# include <cstdio>
# include <algorithm>
# include <cmath>
# include <set>
using namespace std;
long long n,k;
vector <int> d;
vector <int> f;
int main(){
	freopen("TOWER.IN", "r", stdin);
	int T;
	cin>>T;
	int H,L,M=0,sum=0;
	vector<vector<int> > a;
	vector<int> b;
	while(T--){
		sum=0;M=0;
		cin>>H>>L;
		a.clear();b.clear();
		a.resize(H,vector<int>(L));
		b.resize(H);
		for(int i=0;i<H;i++){
			b[i]=0;
			for(int j=0;j<L;j++){
				cin>>a[i][j];
				if(M<a[i][j])M=a[i][j];
			}
		}
		if(M==-1){cout<<-1;return 0;}
		for(int m=1;m<=M;m++){
			for(int i=0;i<H;i++){
				bool f=0;
				int p;
				for(int j=0;j<L;j++){
					if(a[i][j]==m){f=1;p=j;}
				}
				if(f==1){
					int A,B;
					if(b[i]<p){
						A=p-b[i],B=b[i]+L-p;
					}else{
						A=b[i]-p,B=p+L-b[i];
					}
					sum+=min(A*5,B*5);
					sum+=(i*2)*10;
					b[i]=p;
					continue;
				}
			}
		}
		cout<<sum<<endl;
	}
}
/*
2
1 5
-1 2 1 -1 3
3 6
-1 5 6 -1 -1 3
-1 -1 7 -1 2 9 
-1 10 4 1 8 -1

*/