#include <stdio.h>
#include <iostream>
#include <memory.h>

using namespace std;

#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#define ABS(x) ( ((x) < 0) ? (-(x)) : (x) )

void solve()
{
    int H,L;
    cin >> H >> L;
    int arr[51][51];
    int max = 0;
    int level[2555];
    int pos[2555];
    int lpos[55];

    memset(lpos,0,sizeof(lpos));

    for(int i = 0; i < H; i++)
        for(int j = 0; j< L; j++)
        {
            cin >> arr[i][j];
            if (arr[i][j] > max) max = arr[i][j];
            if (arr[i][j] != -1) level[arr[i][j]] = i;
            if (arr[i][j] != -1) pos[arr[i][j]] = j;
        }
    int sum = 0;
    for(int i = 1; i <=max; i++)
    {
        int lvl = level[i];
        int p = pos[i];
        int lp = lpos[lvl];

        int povor = MIN(MIN( ABS(p - lp), ABS(lp + (L-p)) ), ABS(p + (L-lp)));

        //cout << ABS(p - lp) << " " << ABS(lp + (L-p)) << " " << ABS(p + (L-lp))<< endl;
        lpos[lvl] = p;

        sum += povor*5 + level[i]*2*10;


    }
    cout << sum << endl;

}

int main()
{
    //fstream fin("SHADOOF.IN");
    freopen("TOWER.IN", "r",stdin);
    int n;
    cin >> n;
    for(int ii = 0; ii < n; ++ii)
    {
        solve();
    }

    return 0;
}
