import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class Solution {
public static void main
(String[] args
) { int t
= Integer.
parseInt(in.
nextLine()); // Scanner has functions to read ints, longs, strings, chars, etc. for (int i = 1; i <= t; ++i) {
// Square dance
int row = in.nextInt();
int col = in.nextInt();
Dancer[][] dancers = new Dancer[row][col];
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
Dancer d = new Dancer(in.nextInt());
if (r>0) {
d.top = dancers[r-1][c];
dancers[r-1][c].bottom = d;
}
if (c>0) {
d.left = dancers[r][c-1];
dancers[r][c-1].right = d;
}
dancers[r][c] = d;
}
}
System.
out.
println("Case #" + i
+ ": "+squareDance
(dancers
)); }
}
private static int squareDance(Dancer[][] dancers) {
int totalInterest = 0;
while (true) {
int roundInterest = 0;
List
<Dancer
> eliminatedDancers
= new ArrayList(); for (int r=0; r<dancers.length; r++) {
for (int c=0; c<dancers[0].length; c++) {
Dancer d = dancers[r][c];
if (!d.isEliminated) {
roundInterest += d.skill;
} else {
continue;
}
if (!d.isCompeted() || !d.losing()) {
continue;
} else {
eliminatedDancers.add(d);
}
}
}
totalInterest += roundInterest;
if (eliminatedDancers.size() == 0) {
break;
} else {
for (Dancer d: eliminatedDancers) {
eliminateDancer(d);
}
}
}
return totalInterest;
}
private static void eliminateDancer(Dancer d) {
d.isEliminated = true;
if (d.top!=null) {
d.top.bottom = d.bottom;
}
if (d.left!=null) {
d.left.right = d.right;
}
if (d.right!=null) {
d.right.left = d.left;
}
if (d.bottom!=null) {
d.bottom.top = d.top;
}
}
static class Dancer {
private int skill;
private boolean isEliminated = false;
private Dancer top = null;
private Dancer bottom = null;
private Dancer left = null;
private Dancer right = null;
public Dancer(int s) {
skill = s;
}
public boolean isCompeted() {
return (top!=null || bottom!=null || left!=null || right!=null);
}
public boolean losing() {
int skillSum = 0;
int count = 0;
if (top!=null) {
skillSum += top.skill;
count++;
}
if (bottom!=null) {
skillSum += bottom.skill;
count++;
}
if (left!=null) {
skillSum += left.skill;
count++;
}
if (right!=null) {
skillSum += right.skill;
count++;
}
return skill*count < skillSum;
}
}
}