#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int N = 55;
int g[N][N];
int dist[N][N];
bool vis[N][N];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
struct Node {
int x;
int y;
int d;
bool operator<(const Node& t) const {
return d > t.d;
}
};
int main() {
int T;
int r, c;
cin >> T;
for (int C = 1; C <= T; ++C) {
cin >> r >> c;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
cin >> g[i][j];
}
}
memset(dist, 0x3f, sizeof dist);
memset(vis, 0, sizeof vis);
priority_queue<Node> heap;
for (int i = 1; i <= r; ++i) {
heap.push({i, 1, g[i][1]});
dist[i][1] = g[i][1];
heap.push({i, c, g[i][c]});
dist[i][c] = g[i][c];
}
for (int j = 2; j < c; ++j) {
heap.push({1, j, g[1][j]});
dist[1][j] = g[1][j];
heap.push({r, j, g[r][j]});
dist[r][j] = g[r][j];
}
int res = 0;
while (!heap.empty()) {
Node t = heap.top();
heap.pop();
if (vis[t.x][t.y]) {
continue;
}
res += t.d - g[t.x][t.y];
vis[t.x][t.y] = true;
for (int i = 0; i < 4; ++i) {
int x = t.x + dx[i];
int y = t.y + dy[i];
if (x > 0 && x <= r && y > 0 && y <= c) {
if (dist[x][y] > max(t.d, g[x][y])) {
dist[x][y] = max(t.d, g[x][y]);
heap.push({x, y, dist[x][y]});
}
}
}
}
cout << "Case #" << C << ": " << res << endl;
}
return 0;
}