using namespace std;
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdio>
#include <set>
#include <cctype>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <stack>
#include <cctype>
#include <cstring>
#include <string>
#define MAX 200
#define PRIME 31
#define MOD 1000000007
#define PI 3.1415926535897932384
#define F first
#define S second
#define pb push_back
#define mp make_pair
typedef long long ll;
int n, m;
char field[MAX][MAX];
int dist[MAX][MAX];
bool valid(int a, int b){
return (a >= 0 && a < n && b >= 0 && b < m);
}
void bfs(int x, int y){
queue<pair<int, pair<int, int> > > q;
q.push(mp(0, mp(x, y)));
while(!q.empty()){
pair<int, pair<int, int> > p = q.front();
q.pop();
int a = p.S.F, b = p.S.S;
if(dist[a][b] != -1 && dist[a][b] <= p.F) continue;
if(field[a][b] == '1') p.F = 0;
dist[a][b] = p.F;
if(valid(a+1, b) && (dist[a+1][b] == -1 || dist[a+1][b] > dist[a][b]+1)) q.push(mp(dist[a][b]+1, mp(a+1, b)));
if(valid(a, b+1) && (dist[a][b+1] == -1 || dist[a][b+1] > dist[a][b]+1)) q.push(mp(dist[a][b]+1, mp(a, b+1)));
if(valid(a-1, b) && (dist[a-1][b] == -1 || dist[a-1][b] > dist[a][b]+1)) q.push(mp(dist[a][b]+1, mp(a-1, b)));
if(valid(a, b-1) && (dist[a][b-1] == -1 || dist[a][b-1] > dist[a][b]+1)) q.push(mp(dist[a][b]+1, mp(a, b-1)));
}
}
int main(){
//freopen("in.txt", "r", stdin);
int t;
cin >> t;
while(t--){
cin >> n >> m;
memset(dist, -1, sizeof(dist));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
scanf(" %c", &field[i][j]);
}
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(field[i][j] == '1'){ bfs(i, j); break; }
}
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cout << dist[i][j] << " \n"[j == m-1];
}
}
}
return 0;
}
dXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2luY2x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AgICAgIHNjYW5mKCIgJWMiLCAmZmllbGRbaV1bal0pOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBmb3IoaW50IGkgPSAwO2kgPCBuO2krKyl7CiAgICAgICAgICAgIGZvcihpbnQgaiA9IDA7aiA8IG07aisrKXsKICAgICAgICAgICAgICAgIGlmKGZpZWxkW2ldW2pdID09ICcxJyl7IGJmcyhpLCBqKTsgYnJlYWs7IH0KICAgICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgZm9yKGludCBpID0gMDtpIDwgbjtpKyspewogICAgICAgICAgICBmb3IoaW50IGogPSAwO2ogPCBtO2orKyl7CiAgICAgICAgICAgICAgICBjb3V0IDw8IGRpc3RbaV1bal0gPDwgIiBcbiJbaiA9PSBtLTFdOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgfQoKICAgIHJldHVybiAwOwp9Cg==