import java.util.*;
class OptimizedShootingGame {
public static void main
(String[] args
) { Scanner sc
= new Scanner
(System.
in); int t = sc.nextInt(); // number of test cases
while (t-- > 0) {
int n = sc.nextInt(); // number of rows
int m = sc.nextInt(); // number of columns
int[][] mat = new int[n][m]; // matrix to store the shooting board
List<Integer> AarsiRows = new ArrayList<>();
List<Integer> AarsiCols = new ArrayList<>();
List<Integer> KryptoRows = new ArrayList<>();
List<Integer> KryptoCols = new ArrayList<>();
// Read the matrix and store Aarsi's and Krypto's shot positions
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = sc.nextInt();
if (mat[i][j] == 1 || mat[i][j] == 3) {
AarsiRows.add(i);
AarsiCols.add(j);
}
if (mat[i][j] == 2 || mat[i][j] == 3) {
KryptoRows.add(i);
KryptoCols.add(j);
}
}
}
// Sort the rows and columns of the shots
// Create result matrix to store final absolute differences
int[][] res = new int[n][m];
// Calculate the result for each bullseye (i, j)
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int Aarsisum = calculateDistance(AarsiRows, i) + calculateDistance(AarsiCols, j);
int Krysum = calculateDistance(KryptoRows, i) + calculateDistance(KryptoCols, j);
res
[i
][j
] = Math.
abs(Aarsisum
- Krysum
); System.
out.
print(res
[i
][j
] + " "); }
}
}
}
// Function to calculate prefix sum distance for a given axis (rows or columns)
static int calculateDistance(List<Integer> shots, int bullseye) {
int total = 0;
for (int shot : shots) {
total
+= Math.
abs(shot
- bullseye
); }
return total;
}
}