#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>

using namespace std;

int main()
{
    freopen("TOWER.IN", "r", stdin);
    int t,h,l,p[51][51],maxx,ans[2501],x[2501],d[50],m,fl;

    cin >> t;

    maxx=-1;

    for (int k=0; k<t; k++)
    {
       cin >> h >> l;
       for (int i=1; i<=h; ++i)
            for (int j=1; j<=l; ++j)
            {
                cin >> p[i][j];
                if (p[i][j]>maxx)
                    maxx=p[i][j];
                if (p[i][j]!=-1)
                {
                    ans[p[i][j]]=2*(i-1)*10;
                    x[p[i][j]]=j;
                }
            }
            for (int i=1; i<=l; ++i)
                d[i]=1;

            for (int i=1; i<=maxx; ++i)
            {
                fl=((ans[i]/2)/10)+1;
               if (abs(d[fl]-x[i])>l-abs(d[fl]-x[i]))
                    m=l-abs(d[fl]-x[i]);
                else
                    m=abs(d[fl]-x[i]);
                ans[i]+=m*5;
                d[fl]=x[i];
            }

            m=0;

        for (int i=1; i<=maxx; ++i)
            m+=ans[i];

        cout << m << endl;
    }

    return 0;
}
