#include<iostream.h>
struct Node{
int x,y;
}pos[2501];//用来对输入的数据进行预处理,height放在y中,length放在x中;
int turn[50];
int main()
{
int times,height,length;
cin>>times;
while(times--)
{
int tmp,total = 0;
cin>>height>>length;
for(int i = 0 ; i < height ; i++)
for(int j = 0 ; j < length ; j++)
{
cin>>tmp;
if(tmp != -1)//进行预处理!!
{
total++;
pos[tmp].x = j;
pos[tmp].y = i;
}
}
int k = 1;
int curX,curY,ans = 0;
while(k <= total)
{
curY = pos[k].y;
curX = pos[k].x + turn[curY];//当传送带移动一定的位置时,给车辆也相应的移动一定的位置。
if(curX > length)
{
curX %= length;
}
while(curX < 0)
curX += length;
if(curX > length - curX) //寻找最短的路径!!
{
ans += (length-curX)*5 + curY*20;
turn[curY] += length - curX;//设置传送带当前所在位置!!逆时针转动相当于加,顺时针相当于减。
}
else
{
ans +=curX*5 + curY*20;
turn[curY] -= length - curX;
}
k++;
}
cout<<ans<<endl;
for(int m = 0 ; m < 50 ; m++)
turn[m] = 0;
}
return 0;
}