#include<bits/stdc++.h>
using namespace std;
int n,m;
int dis[190][190];
bool visit[190][190];
void bfs(pair<int,int> p)
{
    int fixi=p.first;
    int fixj=p.second;
    memset(visit,false,sizeof(visit));
    queue<pair<int,int> >q;
    q.push(p);
    visit[fixi][fixj]=true;
    while(!q.empty())
    {
        int i=q.front().first;
        int j=q.front().second;
        q.pop();
        dis[i][j]=min(dis[i][j],abs(i-fixi)+abs(j-fixj));

        if(i>0 && !visit[i-1][j])
        {
            q.push(make_pair(i-1,j));
            visit[i-1][j]=true;
        }

        if(j>0 && !visit[i][j-1])
        {
            visit[i][j-1]=true;
            q.push(make_pair(i,j-1));
        }

        if(i<n-1 && !visit[i+1][j])
        {
            q.push(make_pair(i+1,j));
            visit[i+1][j]=true;
        }

        if(j<m-1 && !visit[i][j+1])
        {
            visit[i][j+1]=true;
            q.push(make_pair(i,j+1));
        }
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        queue<pair<int,int> > q1s;
        cin>>n>>m;

        memset(dis,10000,sizeof(dis));
        for(int i=0;i<n;i++)
            {
                string s;
                cin>>s;
                for(int j=0;j<m;j++)
                {
                    if(s[j]=='1')
                    {
                        q1s.push(make_pair(i,j));
                        dis[i][j]=0;
                    }
                }
            }

        while(!q1s.empty())
        {
            bfs(q1s.front());
            q1s.pop();
        }

        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            cout<<dis[i][j]<<" "; //One thing I have figured out is that when I try to print dis for values of
            cout<<"\n";           //i,j larger than n and m it shows some values instead of 0
        }                         //i.e dis table is being filled even for values of i,j greater than n,m
    }

}
/*
1
3 4
0001
0011
0110
*/
