#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
	freopen("tower.in","r", stdin);
	freopen("tower.out","w", stdout);
		
	int test;
	scanf("%d", &test);
		
	int positions[128];

	vector<pair<int, int>> cars(2500);
	
	for(int t = 0; t < test; t++)
	{		
		int h, l;
		scanf("%d%d", &h, &l);
		
		int n = 0;

		for (int i = 0; i < h; i++)
		{
			for (int j = 0; j < l; j++) 
			{
				int car;
				scanf("%d", &car);

				if (car != -1) 
				{
					cars[car - 1].first = i;
					cars[car - 1].second = j;
					n = max(n, car);
				}
			}
		}

		fill(positions, positions + h, 0);

		int res = 0;
		for (int i = 0; i < n; i++) 
		{			
			int floor = cars[i].first;
			int position = cars[i].second;

			res += floor * 2 * 10;
			res += min((position - positions[floor] + l) % l, (positions[floor] - position + l) % l) * 5;
			positions[floor] = position;
		}
		printf("%d\n", res);
		
	}

	return 0;
}

