#include <iostream>
#include <algorithm>
#include <vector>

#define INF 1000000007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, sz[i]);

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>

#define INF 10000000007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++){
        freq[i].push_back(pii(-INF, -1));
        freq[i].push_back(pii(INF, -1));
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    }
    for(i=1;i<=MAXF;i++){
        sort(freq[i].begin(), freq[i].end());
        for(j=1;j<freq[i].size()-1;j++)
            po[freq[i][j].second]=j;
    }

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>

#define INF 1000010007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, sz[i]);

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <ctime>

#define INF 1000000007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++){
        freq[i].push_back(pii(-INF, -1));
        freq[i].push_back(pii(INF, -1));
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    }
    for(i=1;i<=MAXF;i++){
        sort(freq[i].begin(), freq[i].end());
        for(j=1;j<freq[i].size()-1;j++)
            po[freq[i][j].second]=j;
    }

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>

#define INF 1000010007
#define MAXF 10100

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0, ans2=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(INF, -1));

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    /*for(i=1;i<=n;i++)
        for(j=i+1;j<=n;j++){
            int dis=abs(a[i].second.first-a[j].second.first);
            if(min(a[i].first, a[j].first)>=dis && abs(a[i].second.second-a[j].second.second)<=k)
                ans2++;
        }*/

    //cout << ans2 << endl;
    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>

#define INF 1000000000010007
#define MAXF 10100

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0, ans2=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(INF, -1));

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    /*for(i=1;i<=n;i++)
        for(j=i+1;j<=n;j++){
            ll dis=abs(a[i].second.first-a[j].second.first);
            cout << dis << endl;
            cout << min(a[i].first, a[j].first) << endl;
            cout << endl;
            if(min(a[i].first, a[j].first)>=dis && abs(a[i].second.second-a[j].second.second)<=k)
                ans2++;
        }*/

    //cout << ans2 << endl;
    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>

#define INF 1000010007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0, ans2=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    /*for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(INF, -1));

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }*/

    for(i=1;i<=n;i++)
        for(j=i+1;j<=n;j++){
            int dis=abs(a[i].second.first-a[j].second.first);
            if(min(a[i].first, a[j].first)>=dis && abs(a[i].second.second-a[j].second.second)<=k)
                ans2++;
        }

    cout << ans2 << endl;
    //cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>

#define INF 1000010007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0, ans2=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    /*for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(-INF, -1));
    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++)
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    for(i=1;i<=MAXF;i++)
        freq[i].push_back(pii(INF, -1));

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }*/

    for(i=1;i<=n;i++)
        for(j=i+1;j<=n;j++){
            int dis=abs(a[i].second.first-a[j].second.first);
            if(min(a[i].first, a[j].first)>=dis && abs(a[i].second.second-a[j].second.second)<=k)
                ans2++;
        }

    cout << ans2 << endl;
    cout << ans << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <ctime>

#define INF 10000000007
#define MAXF 10010

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pii;
typedef pair<ll, pii> piii;

piii a[100001];

vector<pii> freq[MAXF+1];

vector<ll> BITree[MAXF+1];
ll sz[MAXF+1];
ll po[100001];

ll getSum(ll index, ll pos)
{
    ll sum=0;
    while(index>0)
        sum+=BITree[pos][index], index-=index&(-index);
    return sum;
}

void updateBIT(ll index, ll val, ll pos)
{
    while(index<=sz[pos])
        BITree[pos][index]+=val, index+=index&(-index);
}

void buildfenwick(ll pos, ll s)
{
    ll i;

    for(i=0;i<=s;i++)
        BITree[pos].push_back(0);
}

int main()
{
    ll n, k;
    ll ans=0;
    ll i, j;

    cin >> n >> k;
    for(i=1;i<=n;i++)
        cin >> a[i].second.first >> a[i].first >> a[i].second.second; // x, r, f
    sort(a+1, a+n+1);

    for(i=1;i<=n;i++)
        po[i]=freq[a[i].second.second].size(), freq[a[i].second.second].push_back(pii(a[i].second.first, i));
    for(i=1;i<=MAXF;i++){
        freq[i].push_back(pii(-INF, -1));
        freq[i].push_back(pii(INF, -1));
        sz[i]=freq[i].size(), buildfenwick(i, freq[i].size());
    }
    for(i=1;i<=MAXF;i++){
        sort(freq[i].begin(), freq[i].end());
        for(j=1;j<freq[i].size()-1;j++)
            po[freq[i][j].second]=j;
    }

    for(i=1;i<=n;i++){
        ll x=a[i].second.first, r=a[i].first, f=a[i].second.second;
        updateBIT(po[i], -1, f);
        for(j=-k;j<=k;j++){
            ll cur=f+j;
            if(cur<=0)
                continue;
            ll lo=1, hi=freq[cur].size(), m;
            while(lo<hi){
                m=(lo+hi)/2;
                if(freq[cur][m].first<x-r)
                    lo=m+1;
                else
                    hi=m;
            }
            ll lo2=1, hi2=freq[cur].size(), m2;
            while(lo2<hi2){
                m2=(lo2+hi2)/2;
                if(freq[cur][m2].first<=x+r)
                    lo2=m2+1;
                else
                    hi2=m2;
            }
            ans+=(lo2-lo)+(getSum(lo2-1, cur)-getSum(lo-1, cur));
        }
    }

    cout << ans << endl;

    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

typedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef vector<int> vi;
typedef long long ll;

#define pb push_back
#define inf 0x3f3f3f3f
#define all(v) (v).begin() , (v).end()
#define ones(n) __builtin_popcount(n)
#define watch(x) cout << (#x) << " is " << (x) << endl
#define mask bitset<80>

int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, -1, 1, 1, -1};

const int N = 1e5 + 5;
int n, k, sz = 0;
int x[N], r[N], f[N], ind[N], nums[3 * N];

ordered_set segTree[4 * N];

int query(int s, int e, int l = 0, int r = sz - 1, int pos = 1) {
    if (segTree[pos].size() == 0 || l > e || r < s)
        return 0;
    if (l >= s && r <= e)
         return segTree[pos].size() - segTree[pos].order_of_key({e, -inf});
    int mid = l + ((r - l) >> 1);
    return query(s, e, l, mid, pos * 2) + query(s, e, mid + 1, r, pos * 2 + 1);
}

void in(int x, int d, int l = 0, int r = sz - 1, int pos = 1) {
    segTree[pos].insert({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return in(x, d, l, mid, pos * 2);
    in(x, d, mid + 1, r, pos * 2 + 1);
}

void del(int x, int d, int l = 0, int r = sz - 1, int pos = 1) {
    segTree[pos].erase({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return del(x, d, l, mid, pos * 2);
    del(x, d, mid + 1, r, pos * 2 + 1);
}

int nw(int old) {
    return lower_bound(nums, nums + sz, old) - nums;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", x + i, r + i, f + i), ind[i] = i;
        nums[sz++] = x[i];
        nums[sz++] = x[i] + r[i];
        nums[sz++] = x[i] - r[i];
    }

    sort(nums, nums + sz);
    sz = unique(nums, nums + sz) - nums;

    sort(ind, ind + n, [](int i, int j) {
        return f[i] < f[j];
    });

    int l = 0;
    ll ans = 0;
    for (int j = 0, i = ind[j]; j < n; j++, i = ind[j]) {
        while (f[i] - f[ind[l]] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l++;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));

        in(nw(x[i]), nw(x[i] + r[i]));
    }

    for (int i = 0 ;i < 4 * N ;i++)
        segTree[i].clear();

    l = n - 1;
    for (int j = n - 1, i = ind[j]; j >= 0; j--, i = ind[j]) {
        while (f[ind[l]] - f[i] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l--;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));
        in(nw(x[i]), nw(x[i] + r[i]));
    }

    printf("%lld", ans);
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

typedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef vector<int> vi;
typedef long long ll;

#define pb push_back
#define inf 0x3f3f3f3f
#define all(v) (v).begin() , (v).end()
#define ones(n) __builtin_popcount(n)
#define watch(x) cout << (#x) << " is " << (x) << endl
#define mask bitset<80>

int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, -1, 1, 1, -1};

const int N = 1e5 + 5;
int n, k , sz = 0;
int x[N], r[N], f[N], ind[N] , nums[3 * N];

struct node {
    ordered_set OS;
    node *left, *right;
    node() : left(0), right(0) {}
};

node *root = 0;

int query(int s, int e, node *cur = root, int l = 0 , int r = sz - 1) {
    if (cur == 0 || l > e || r < s)
        return 0;
    if (l >= s && r <= e)
        return cur->OS.size() - cur->OS.order_of_key({e, -inf});
    int mid = l + ((r - l) >> 1);
    return query(s, e, cur->left, l, mid) + query(s, e, cur->right, mid + 1, r);
}

void in(int x, int d, node *&cur = root, int l = 0 , int r = sz - 1) {
    if (cur == 0)
        cur = new node;
    cur->OS.insert({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return in(x, d, cur->left, l, mid);
    in(x, d, cur->right, mid + 1, r);
}

void del(int x, int d , node *cur = root, int l = 0 , int r = sz - 1) {
    cur->OS.erase({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return del(x, d, cur->left, l, mid);
    del(x, d, cur->right, mid + 1, r);
}

int nw(int old) {
    return lower_bound(nums , nums + sz , old) - nums;
}
int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", x + i, r + i, f + i), ind[i] = i;
        nums[sz++] = x[i];
        nums[sz++] = x[i] + r[i];
        nums[sz++] = x[i] - r[i];
    }

    sort(nums , nums + sz);
    sz = unique(nums , nums + sz) - nums;

    sort(ind, ind + n, [](int i, int j) {
        return f[i] < f[j];
    });

    int l = 0;
    ll ans = 0;
    for (int j = 0, i = ind[j]; j < n; j++, i = ind[j]) {
        while (f[i] - f[ind[l]] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l++;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));

        in(nw(x[i]), nw(x[i] + r[i]));
    }

    root = new node;

    l = n - 1;
    for (int j = n - 1, i = ind[j]; j >= 0; j--, i = ind[j]) {
        while (f[ind[l]] - f[i] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l--;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));
        in(nw(x[i]), nw(x[i] + r[i]));
    }

    printf("%lld", ans);
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

typedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef vector<int> vi;
typedef long long ll;

#define pb push_back
#define inf 0x3f3f3f3f
#define all(v) (v).begin() , (v).end()
#define ones(n) __builtin_popcount(n)
#define watch(x) cout << (#x) << " is " << (x) << endl

int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, -1, 1, 1, -1};

const int N = 1e5 + 5;
int n, k, sz = 0;
int x[N], r[N], f[N], ind[N], nums[3 * N];

ordered_set segTree[12 * N];

int query(int s, int e, int l = 0, int r = sz - 1, int pos = 1) {
    if (segTree[pos].size() == 0 || l > e || r < s)
        return 0;
    if (l >= s && r <= e)
         return segTree[pos].size() - segTree[pos].order_of_key({e, -inf});
    int mid = l + ((r - l) >> 1);
    return query(s, e, l, mid, pos * 2) + query(s, e, mid + 1, r, pos * 2 + 1);
}

void in(int x, int d, int l = 0, int r = sz - 1, int pos = 1) {
    segTree[pos].insert({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return in(x, d, l, mid, pos * 2);
    in(x, d, mid + 1, r, pos * 2 + 1);
}

void del(int x, int d, int l = 0, int r = sz - 1, int pos = 1) {
    segTree[pos].erase({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return del(x, d, l, mid, pos * 2);
    del(x, d, mid + 1, r, pos * 2 + 1);
}

inline int nw(int old) {
    return lower_bound(nums, nums + sz, old) - nums;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "w", stdout);
#endif
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", x + i, r + i, f + i), ind[i] = i;
        nums[sz++] = x[i];
        nums[sz++] = x[i] + r[i];
        nums[sz++] = x[i] - r[i];
    }

    sort(nums, nums + sz);
    sz = unique(nums, nums + sz) - nums;

    sort(ind, ind + n, [](int i, int j) {
        return f[i] < f[j];
    });

    int l = 0;
    ll ans = 0;
    for (int j = 0, i = ind[j]; j < n; j++, i = ind[j]) {
        while (f[i] - f[ind[l]] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l++;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));

        in(nw(x[i]), nw(x[i] + r[i]));
    }

    for (int i = 0 ;i < 4 * N ;i++)
        segTree[i].clear();

    l = n - 1;
    for (int j = n - 1, i = ind[j]; j >= 0; j--, i = ind[j]) {
        while (f[ind[l]] - f[i] > k) {
            del(nw(x[ind[l]]), nw(x[ind[l]] + r[ind[l]]));
            l--;
        }

        ans += query(nw(x[i] - r[i]), nw(x[i]));
        in(nw(x[i]), nw(x[i] + r[i]));
    }

    printf("%lld", ans);
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

typedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef vector<int> vi;
typedef long long ll;

#define pb push_back
#define inf 0x3f3f3f3f
#define all(v) (v).begin() , (v).end()
#define ones(n) __builtin_popcount(n)
#define watch(x) cout << (#x) << " is " << (x) << endl
#define mask bitset<80>

int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, -1, 1, 1, -1};

const int N = 1e5 + 5;
int n, k;
int x[N], r[N], f[N], ind[N];

struct node {
    ordered_set OS;
    node *left, *right;

    node() : left(0), right(0) {}
};

node *root = 0;

int query(int s, int e, node *cur = root, int l = -inf, int r = inf) {
    if (cur == 0 || l > e || r < s)
        return 0;
    if (l >= s && r <= e)
        return cur->OS.size() - cur->OS.order_of_key({e, -inf});
    int mid = l + ((r - l) >> 1);
    return query(s, e, cur->left, l, mid) + query(s, e, cur->right, mid + 1, r);
}

void in(int x, int d, node *&cur = root, int l = -inf, int r = inf) {
    if (cur == 0)
        cur = new node;
    cur->OS.insert({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return in(x, d, cur->left, l, mid);
    in(x, d, cur->right, mid + 1, r);
}

void del(int x, int d , node *cur = root, int l = -inf, int r = inf) {
    cur->OS.erase({d, x});
    if (l == r)
        return;
    int mid = l + ((r - l) >> 1);
    if (x <= mid)
        return del(x, d, cur->left, l, mid);
    del(x, d, cur->right, mid + 1, r);
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++)
        scanf("%d%d%d", x + i, r + i, f + i), ind[i] = i;

    sort(ind, ind + n, [](int i, int j) {
        return f[i] < f[j];
    });

    int l = 0;
    ll ans = 0;
    for (int j = 0, i = ind[j]; j < n; j++, i = ind[j]) {
        while (f[i] - f[ind[l]] > k) {
            del(x[ind[l]], x[ind[l]] + r[ind[l]]);
            l++;
        }

        ans += query(x[i] - r[i], x[i]);

        in(x[i], x[i] + r[i]);
    }

    root = new node;

    l = n - 1;
    for (int j = n - 1, i = ind[j]; j >= 0; j--, i = ind[j]) {
        while (f[ind[l]] - f[i] > k) {
            del(x[ind[l]], x[ind[l]] + r[ind[l]]);
            l--;
        }

        ans += query(x[i] - r[i], x[i]);
        in(x[i], x[i] + r[i]);
    }

    printf("%lld", ans);
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef vector<int> vi;
typedef long long ll;

#define pb push_back
#define inf 0x3f3f3f3f
#define all(v) (v).begin() , (v).end()
#define ones(n) __builtin_popcount(n)
#define watch(x) cout << (#x) << " is " << (x) << endl

int di[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dj[] = {1, -1, 0, 0, -1, 1, 1, -1};

const int N = 1e5 + 5 , M = 1e4 + 5;
int n, k;
int x[N], r[N], f[N], ind[N] ;
ordered_set<int> freq[M];

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "w", stdout);
#endif
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", x + i, r + i, f + i), ind[i] = i;
    }

    sort(ind, ind + n, [](int i, int j) {
        return r[i] > r[j];
    });

    ll ans = 0;
    for (int j = 0 , i = ind[j] ;j < n ;j++ , i = ind[j]) {
        for (int h = max(1 , f[i] - k) ;h <= min(M - 1 , f[i] + k) ;h++) {
            ans += freq[h].order_of_key(x[i] + r[i] + 1) - freq[h].order_of_key(x[i] - r[i]);
        }
        freq[f[i]].insert(x[i]);
    }

    printf("%lld" , ans);
}


def main():
    t = int(input())
    for i_t in range(t):
        n, m = _read_ints()
        a = tuple(tuple(_read_ints()) for i_row in range(n))
        result = _find_fixed_matrix(a)
        for row in result:
            print(*row)

def _find_fixed_matrix(matrix):
    rows_n = len(matrix)
    columns_n = len(matrix[0])
    elements_n = rows_n * columns_n

    result = tuple(map(list, matrix))

    actions = tuple([None]*columns_n for i_row in range(rows_n))
    queue = []
    i_action = 0

    for i_row in range(rows_n):
        for i_column in range(columns_n):
            if actions[i_row][i_column] is None:
                actions[i_row][i_column] = 1
                queue.append(((i_row, i_column), 1))

                while i_action != len(queue):
                    (u, v), action = queue[i_action]
                    i_action += 1
                    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                               and actions[u+du][v+dv] is None:
                            try:
                                action = _try_choose_action((u+du, v+dv), matrix, actions)
                            except ValueError:
                                pass
                            else:
                                actions[u+du][v+dv] = action
                                queue.append(((u+du, v+dv), action))
            result[i_row][i_column] += actions[i_row][i_column]

    return result

def _try_choose_action(pos, matrix, actions):
    rows_n = len(matrix)
    columns_n = len(matrix[0])

    u, v = pos
    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                and actions[u+du][v+dv] is not None:
            new_value = matrix[u+du][v+dv] + actions[u+du][v+dv]
            if matrix[u][v] == new_value:
                return 1
            elif matrix[u][v] + 1 == new_value:
                return 0

    raise ValueError

def _read_ints():
    return map(int, input().split())

if __name__ == "__main__":
    main()


def main():
    t = int(input())
    for i_t in range(t):
        n, m = _read_ints()
        a = tuple(tuple(_read_ints()) for i_row in range(n))
        result = _find_fixed_matrix(a)
        for row in result:
            print(*row)

def _find_fixed_matrix(matrix):
    rows_n = len(matrix)
    columns_n = len(matrix[0])
    elements_n = rows_n * columns_n

    actions = tuple([None]*columns_n for i_row in range(rows_n))
    actions[0][0] = 1
    queue = [((0, 0), 1)]
    i_action = 0

    while len(queue) != elements_n:
        (u, v), action = queue[i_action]
        i_action += 1
        for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                   and actions[u+du][v+dv] is None:
                try:
                    action = _try_choose_action((u+du, v+dv), matrix, actions)
                except ValueError:
                    pass
                else:
                    actions[u+du][v+dv] = action
                    queue.append(((u+du, v+dv), action))
        if i_action == len(queue):
            for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                       and actions[u+du][v+dv] is None:
                    action = 1
                    actions[u+du][v+dv] = action
                    queue.append(((u+du, v+dv), action))
                    break

    result = tuple(map(list, matrix))
    for (u, v), action in queue:
        result[u][v] += action
    return result

def _try_choose_action(pos, matrix, actions):
    rows_n = len(matrix)
    columns_n = len(matrix[0])

    u, v = pos
    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                and actions[u+du][v+dv] is not None:
            new_value = matrix[u+du][v+dv] + actions[u+du][v+dv]
            if matrix[u][v] == new_value:
                return 1
            elif matrix[u][v] + 1 == new_value:
                return 0

    raise ValueError

def _read_ints():
    return map(int, input().split())

if __name__ == "__main__":
    main()


def main():
    t = int(input())
    for i_t in range(t):
        n, m = _read_ints()
        a = tuple(tuple(_read_ints()) for i_row in range(n))
        result = _find_fixed_matrix(a)
        for row in result:
            print(*row)

def _find_fixed_matrix(matrix):
    rows_n = len(matrix)
    columns_n = len(matrix[0])
    elements_n = rows_n * columns_n

    actions = tuple([None]*columns_n for i_row in range(rows_n))
    queue = [((0, 0), 1)]
    i_action = 0

    while len(queue) != elements_n:
        (u, v), action = queue[i_action]
        i_action += 1
        actions[u][v] = action
        for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                   and actions[u+du][v+dv] is None:
                try:
                    action = _try_choose_action((u+du, v+dv), matrix, actions)
                except ValueError:
                    pass
                else:
                    queue.append(((u+du, v+dv), action))
        if i_action == len(queue):
            for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                       and actions[u+du][v+dv] is None:
                    queue.append(((u+du, v+dv), 1))
                    break

    result = tuple(map(list, matrix))
    for (u, v), action in queue:
        result[u][v] += action
    return result

def _try_choose_action(pos, matrix, actions):
    rows_n = len(matrix)
    columns_n = len(matrix[0])

    u, v = pos
    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                and actions[u+du][v+dv] is not None:
            new_value = matrix[u+du][v+dv] + actions[u+du][v+dv]
            if matrix[u][v] == new_value:
                return 1
            elif matrix[u][v] + 1 == new_value:
                return 0

    raise ValueError

def _read_ints():
    return map(int, input().split())

if __name__ == "__main__":
    main()


def main():
    t = int(input())
    for i_t in range(t):
        n, m = _read_ints()
        a = tuple(tuple(_read_ints()) for i_row in range(n))
        result = _find_fixed_matrix(a)
        for row in result:
            print(*row)

def _find_fixed_matrix(matrix):
    rows_n = len(matrix)
    columns_n = len(matrix[0])
    elements_n = rows_n * columns_n

    actions = tuple([None]*columns_n for i_row in range(rows_n))
    queue = []
    i_action = 0

    for u in range(rows_n):
        for v in range(columns_n):
            if actions[u][v] is None:
                actions[u][v] = 1
                queue.append(((u, v), 1))

                while i_action != len(queue):
                    (u, v), action = queue[i_action]
                    i_action += 1
                    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                               and actions[u+du][v+dv] is None:
                            try:
                                action = _try_choose_action((u+du, v+dv), matrix, actions)
                            except ValueError:
                                pass
                            else:
                                actions[u+du][v+dv] = action
                                queue.append(((u+du, v+dv), action))

    result = tuple(map(list, matrix))
    for (u, v), action in queue:
        result[u][v] += action
    return result

def _try_choose_action(pos, matrix, actions):
    rows_n = len(matrix)
    columns_n = len(matrix[0])

    u, v = pos
    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                and actions[u+du][v+dv] is not None:
            new_value = matrix[u+du][v+dv] + actions[u+du][v+dv]
            if matrix[u][v] == new_value:
                return 1
            elif matrix[u][v] + 1 == new_value:
                return 0

    raise ValueError

def _read_ints():
    return map(int, input().split())

if __name__ == "__main__":
    main()


def main():
    t = int(input())
    for i_t in range(t):
        n, m = _read_ints()
        a = tuple(tuple(_read_ints()) for i_row in range(n))
        result = _find_fixed_matrix(a)
        for row in result:
            print(*row)

def _find_fixed_matrix(matrix):
    rows_n = len(matrix)
    columns_n = len(matrix[0])
    elements_n = rows_n * columns_n

    actions = tuple([None]*columns_n for i_row in range(rows_n))
    actions[0][0] = 1
    queue = [((0, 0), 1)]
    i_action = 0

    while len(queue) != elements_n:
        (u, v), action = queue[i_action]
        i_action += 1
        for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                   and actions[u+du][v+dv] is None:
                try:
                    action = _try_choose_action((u+du, v+dv), matrix, actions)
                except ValueError:
                    pass
                else:
                    actions[u+du][v+dv] = action
                    queue.append(((u+du, v+dv), action))
        while i_action == len(queue):
            for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                       and actions[u+du][v+dv] is None:
                    action = 1
                    actions[u+du][v+dv] = action
                    queue.append(((u+du, v+dv), action))
                    break

    result = tuple(map(list, matrix))
    for (u, v), action in queue:
        result[u][v] += action
    return result

def _try_choose_action(pos, matrix, actions):
    rows_n = len(matrix)
    columns_n = len(matrix[0])

    u, v = pos
    for du, dv in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        if 0 <= u+du < rows_n and 0 <= v+dv < columns_n \
                and actions[u+du][v+dv] is not None:
            new_value = matrix[u+du][v+dv] + actions[u+du][v+dv]
            if matrix[u][v] == new_value:
                return 1
            elif matrix[u][v] + 1 == new_value:
                return 0

    raise ValueError

def _read_ints():
    return map(int, input().split())

if __name__ == "__main__":
    main()


for _ in range(int(input())):
	row, column = map(int, input().split())
	grid = []
	for r in range(row):
		l = list(map(int, input().split()))
		grid.append(l)

	for r in range(row):
		for c in range(column):
			if (r+c) % 2 == 0:
				if grid[r][c] % 2 == 0:
					continue
				else:
					grid[r][c] += 1
			else:
				if grid[r][c] % 2 == 1:
					continue
				else:
					grid[r][c] += 1

	for r in grid:
		print(*r)


from math import *
from bisect import *
from collections import *
from random import *
from decimal import *
from random import *
import sys
input=sys.stdin.readline
def inp():
    return int(input())
def st():
    return input().rstrip('\n')
def lis():
    return list(map(int,input().split()))
def ma():
    return map(int,input().split())
t=inp()
while(t):
    t-=1
    n,m=ma()
    r=[]
    for i in range(n):
        a=lis()
        r.append(a)
    for i in range(n):
        for j in range(m):
            if((i+j)%2):
                r[i][j]+=r[i][j]%2
            else:
                r[i][j]+=r[i][j]%2 ^ 1
    for i in r:
        print(*i)


from math import *
from bisect import *
from collections import *
from random import *
from decimal import *
import sys
input=sys.stdin.readline
def inp():
    return int(input())
def st():
    return input().rstrip('\n')
def lis():
    return list(map(int,input().split()))
def ma():
    return map(int,input().split())
t=inp()
while(t):
    t-=1
    n,m=ma()
    a=[]
    for i in range(n):
        aa=lis()
        a.append(aa)
    for i in range(n):
        for j in range(m):
            fl=0
            if(i==0 and j==0):
                a[i][j]+=1
            elif(j==(m-1) and i==0):
                if(m>1 and a[0][j-1]==a[i][j]):
                    a[i][j]+=1
                else:
                    if(m>1 and (a[i][j]+1)!=a[i][j-1]):
                        a[i][j]+=1

            elif(i==(n-1) and j==0):
                if(n>1 and a[n-2][j]==a[i][j]):
                    a[i][j]+=1
                elif(n>1 and a[n-2][j]!=(a[i][j]+1)):
                    a[i][j]+=1
            elif(j==(m-1) and i==(n-1)):
                if(m>1 and a[i][j-1]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                if(n>1 and a[n-2][j]==a[i][j] and fl==0):
                    a[i][j]+=1
            elif(i==0):
                if(a[i][j-1]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                elif(a[i][j-1]!=(a[i][j]+1)):
                    a[i][j]+=1
            elif(i==(n-1)):
                if(a[i][j-1]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                elif(fl==0 and a[i-1][j]==a[i][j]):
                    a[i][j]+=1
                elif((a[i][j]+1)!=a[i-1][j] and (a[i][j]+1)!=a[i][j-1]):
                    a[i][j]+=1
            elif(j==0):
                if(a[i-1][j]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                elif((a[i][j]+1)!=a[i-1][j]):
                    a[i][j]+=1
            elif(j==(m-1)):
                if(a[i-1][j]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                elif(fl==0 and a[i][j-1]==a[i][j]):
                    a[i][j]+=1
                elif((a[i][j]+1)!=a[i][j-1] and (a[i][j]+1)!=a[i-1][j]):
                    a[i][j]+=1
            else:
                if(a[i-1][j]==a[i][j]):
                    fl=1
                    a[i][j]+=1
                elif(fl==0 and a[i][j-1]==a[i][j]):
                    a[i][j]+=1
                    fl=1
                elif((a[i][j]+1)!=a[i-1][j] and (a[i][j]+1)!=a[i][j-1]):
                    a[i][j]+=1
    for i in a:
        print(*i)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush,heappop,heapify
from itertools import permutations,combinations
mod = int(1e9)+7

ip = lambda : int(stdin.readline())
inp = lambda: map(int,stdin.readline().split())
ips = lambda: stdin.readline().rstrip()
out = lambda x : stdout.write(str(x)+"\n")

t = ip()
for _ in range(t):
    n,m = inp()
    arr = []
    for i in range(n):
        ch = list(inp())
        #ch = [[i,i+1] for i in ch]
        arr.append(ch)
    xor = 0
    for i in range(n):
        if xor == 0:
            for j in range(m):
                if j%2 == 0:
                    if arr[i][j]%2 != 0:
                        arr[i][j] += 1
                else:
                    if ch[j]%2 == 0:
                        arr[i][j] += 1
        else:
            for j in range(m):
                if j%2 == 1:
                    if arr[i][j]%2 != 0:
                        arr[i][j] += 1
                else:
                    if arr[i][j]%2 == 0:
                        arr[i][j] += 1
        xor ^= 1
    for i in arr:
        print(*i)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush,heappop,heapify
from itertools import permutations,combinations
mod = int(1e9)+7

ip = lambda : int(stdin.readline())
inp = lambda: map(int,stdin.readline().split())
ips = lambda: stdin.readline().rstrip()
out = lambda x : stdout.write(str(x)+"\n")

t = ip()
for _ in range(t):
    n,m = inp()
    arr = []
    for i in range(n):
        ch = list(inp())
        #ch = [[i,i+1] for i in ch]
        arr.append(ch)
    xor = 0
    for i in range(n):
        if xor == 0:
            for j in range(m):
                if j%2 == 0:
                    if arr[i][j]%2 != 0:
                        arr[i][j] += 1
                else:
                    if arr[i][j]%2 == 0:
                        arr[i][j] += 1
        else:
            for j in range(m):
                if j%2 == 1:
                    if arr[i][j]%2 != 0:
                        arr[i][j] += 1
                else:
                    if arr[i][j]%2 == 0:
                        arr[i][j] += 1
        xor ^= 1
    for i in arr:
        print(*i)


t = int(input())
for _ in range(t):
	n, m = map(int, input().split())
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			if (i+j)%2 != a[j]%2:
				a[j] += 1
		print(' '.join(str(x) for x in a))


t = int(input())
for _ in range(t):
	n, m = map(int, input().split())
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			a[j] += (i+j)%2 != a[j]%2
		print(*a)


for _ in range(int(input())):
    n,m=map(int,input().split())
    a=[]
    for i in range(n):
        b=list(map(int,input().split()))
        a.append(b)
    for i in range(n):
        count=0
        if i%2!=0:
            count=1
        for j in range(m):
            if count%2==0:
                if (a[i][j]%2)!=0:
                    a[i][j]+=1
            else:
                if (a[i][j]%2)==0:
                    a[i][j]+=1
            count+=1
    for i in range(n):
        print(*a[i])


import time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import deque
from collections import defaultdict
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
    return int(stdin.readline())
def IP(): # to take tuple as input
    return map(int,stdin.readline().split())
def L(): # to take list as input
    return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
    return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
    return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
    return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
    if a==0:
        return b
    elif b==0:
        return a
    if a>b:
        return gcd(a%b,b)
    else:
        return gcd(a,b%a)
def bfs(adj,v): # a schema of bfs
    visited=[False]*(v+1)
    q=deque()
    while q:
        pass
def sieve():
    li=[True]*(2*(10**5)+5)
    li[0],li[1]=False,False
    for i in range(2,len(li),1):
        if li[i]==True:
            for j in range(i*i,len(li),i):
                li[j]=False
    prime=[]
    for i in range((2*(10**5)+5)):
        if li[i]==True:
            prime.append(i)
    return prime
def setBit(n):
    count=0
    while n!=0:
        n=n&(n-1)
        count+=1
    return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
    spf[1]=1
    for i in range(2,mx+1):
        if spf[i]==mx:
            spf[i]=i
            for j in range(i*i,mx+1,i):
                if i<spf[j]:
                    spf[j]=i
    return
def readTree(n,e): # to read tree
    adj=[set() for i in range(n+1)]
    for i in range(e):
        u1,u2=IP()
        adj[u1].add(u2)
    return adj
#####################################################################################
mod=10**9+7
def solve():
    n,m=IP()
    li=[]
    for i in range(n):
        temp=L()
        li.append(temp)
    for i in range(n):
        for j in range(m):
            if (i+j)%2 and (li[i][j]%2==0):
                li[i][j]+=1
            elif (i+j)%2==0 and li[i][j]%2==1:
                li[i][j]+=1
    for ele in li:
        print(*ele)

t=II()
for i in range(t):
    solve()

    #######
   #
  #
 #######   #     #  # ####   # #     #
       #  # #   #  # #   #  # # #   #
      #  ####  #  # ####   ####  # #
######  #   # #### #    # #   #   #

# ``````¶0````1¶1_```````````````````````````````````````
# ```````¶¶¶0_`_¶¶¶0011100¶¶¶¶¶¶¶001_````````````````````
# ````````¶¶¶¶¶00¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0_````````````````
# `````1_``¶¶00¶0000000000000000000000¶¶¶¶0_`````````````
# `````_¶¶_`0¶000000000000000000000000000¶¶¶¶¶1``````````
# ```````¶¶¶00¶00000000000000000000000000000¶¶¶_`````````
# ````````_¶¶00000000000000000000¶¶00000000000¶¶`````````
# `````_0011¶¶¶¶¶000000000000¶¶00¶¶0¶¶00000000¶¶_````````
# ```````_¶¶¶¶¶¶¶00000000000¶¶¶¶0¶¶¶¶¶00000000¶¶1````````
# ``````````1¶¶¶¶¶000000¶¶0¶¶¶¶¶¶¶¶¶¶¶¶0000000¶¶¶````````
# ```````````¶¶¶0¶000¶00¶0¶¶`_____`__1¶0¶¶00¶00¶¶````````
# ```````````¶¶¶¶¶00¶00¶10¶0``_1111_`_¶¶0000¶0¶¶¶````````
# ``````````1¶¶¶¶¶00¶0¶¶_¶¶1`_¶_1_0_`1¶¶_0¶0¶¶0¶¶````````
# ````````1¶¶¶¶¶¶¶0¶¶0¶0_0¶``100111``_¶1_0¶0¶¶_1¶````````
# ```````1¶¶¶¶00¶¶¶¶¶¶¶010¶``1111111_0¶11¶¶¶¶¶_10````````
# ```````0¶¶¶¶__10¶¶¶¶¶100¶¶¶0111110¶¶¶1__¶¶¶¶`__````````
# ```````¶¶¶¶0`__0¶¶0¶¶_¶¶¶_11````_0¶¶0`_1¶¶¶¶```````````
# ```````¶¶¶00`__0¶¶_00`_0_``````````1_``¶0¶¶_```````````
# ``````1¶1``¶¶``1¶¶_11``````````````````¶`¶¶````````````
# ``````1_``¶0_¶1`0¶_`_``````````_``````1_`¶1````````````
# ``````````_`1¶00¶¶_````_````__`1`````__`_¶`````````````
# ````````````¶1`0¶¶_`````````_11_`````_``_``````````````
# `````````¶¶¶¶000¶¶_1```````_____```_1``````````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶0_``````_````_1111__``````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶01_`````_11____1111_```````````
# `````````¶¶0¶0¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1101_______11¶_```````````
# ``````_¶¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0¶0¶¶¶1````````````
# `````0¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1`````````````
# ````0¶0000000¶¶0_````_011_10¶110¶01_1¶¶¶0````_100¶001_`
# ```1¶0000000¶0_``__`````````_`````````0¶_``_00¶¶010¶001
# ```¶¶00000¶¶1``_01``_11____``1_``_`````¶¶0100¶1```_00¶1
# ``1¶¶00000¶_``_¶_`_101_``_`__````__````_0000001100¶¶¶0`
# ``¶¶¶0000¶1_`_¶``__0_``````_1````_1_````1¶¶¶0¶¶¶¶¶¶0```
# `_¶¶¶¶00¶0___01_10¶_``__````1`````11___`1¶¶¶01_````````
# `1¶¶¶¶¶0¶0`__01¶¶¶0````1_```11``___1_1__11¶000`````````
# `1¶¶¶¶¶¶¶1_1_01__`01```_1```_1__1_11___1_``00¶1````````
# ``¶¶¶¶¶¶¶0`__10__000````1____1____1___1_```10¶0_```````
# ``0¶¶¶¶¶¶¶1___0000000```11___1__`_0111_```000¶01```````
# ```¶¶¶00000¶¶¶¶¶¶¶¶¶01___1___00_1¶¶¶`_``1¶¶10¶¶0```````
# ```1010000¶000¶¶0100_11__1011000¶¶0¶1_10¶¶¶_0¶¶00``````
# 10¶000000000¶0________0¶000000¶¶0000¶¶¶¶000_0¶0¶00`````
# ¶¶¶¶¶¶0000¶¶¶¶_`___`_0¶¶¶¶¶¶¶00000000000000_0¶00¶01````
# ¶¶¶¶¶0¶¶¶¶¶¶¶¶¶_``_1¶¶¶00000000000000000000_0¶000¶01```
# 1__```1¶¶¶¶¶¶¶¶¶00¶¶¶¶00000000000000000000¶_0¶0000¶0_``
# ```````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000010¶00000¶¶_`
# ```````0¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000¶10¶¶0¶¶¶¶¶0`
# ````````¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000000010¶¶¶0011```
# ````````1¶¶¶¶¶¶¶¶¶¶0¶¶¶0000000000000000000¶100__1_`````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶000000000000000000¶11``_1``````
# `````````1¶¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000¶11___1_`````
# ``````````¶¶¶¶¶¶0¶0¶¶¶¶¶¶¶0000000000000000¶11__``1_````
# ``````````¶¶¶¶¶¶¶0¶¶¶0¶¶¶¶¶000000000000000¶1__````__```
# ``````````¶¶¶¶¶¶¶¶0¶¶¶¶¶¶¶¶¶0000000000000000__`````11``
# `````````_¶¶¶¶¶¶¶¶¶000¶¶¶¶¶¶¶¶000000000000011_``_1¶¶¶0`
# `````````_¶¶¶¶¶¶0¶¶000000¶¶¶¶¶¶¶000000000000100¶¶¶¶0_`_
# `````````1¶¶¶¶¶0¶¶¶000000000¶¶¶¶¶¶000000000¶00¶¶01`````
# `````````¶¶¶¶¶0¶0¶¶¶0000000000000¶0¶00000000011_``````_
# ````````1¶¶0¶¶¶0¶¶¶¶¶¶¶000000000000000000000¶11___11111
# ````````¶¶¶¶0¶¶¶¶¶00¶¶¶¶¶¶000000000000000000¶011111111_
# ```````_¶¶¶¶¶¶¶¶¶0000000¶0¶00000000000000000¶01_1111111
# ```````0¶¶¶¶¶¶¶¶¶000000000000000000000000000¶01___`````
# ```````¶¶¶¶¶¶0¶¶¶000000000000000000000000000¶01___1````
# ``````_¶¶¶¶¶¶¶¶¶00000000000000000000000000000011_111```
# ``````0¶¶0¶¶¶0¶¶0000000000000000000000000000¶01`1_11_``
# ``````¶¶¶¶¶¶0¶¶¶0000000000000000000000000000001`_0_11_`
# ``````¶¶¶¶¶¶¶¶¶00000000000000000000000000000¶01``_0_11`
# ``````¶¶¶¶0¶¶¶¶00000000000000000000000000000001```_1_11


import time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import deque
from collections import defaultdict
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
    return int(stdin.readline())
def IP(): # to take tuple as input
    return map(int,stdin.readline().split())
def L(): # to take list as input
    return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
    return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
    return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
    return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
    if a==0:
        return b
    elif b==0:
        return a
    if a>b:
        return gcd(a%b,b)
    else:
        return gcd(a,b%a)
def bfs(adj,v): # a schema of bfs
    visited=[False]*(v+1)
    q=deque()
    while q:
        pass
def sieve():
    li=[True]*(2*(10**5)+5)
    li[0],li[1]=False,False
    for i in range(2,len(li),1):
        if li[i]==True:
            for j in range(i*i,len(li),i):
                li[j]=False
    prime=[]
    for i in range((2*(10**5)+5)):
        if li[i]==True:
            prime.append(i)
    return prime
def setBit(n):
    count=0
    while n!=0:
        n=n&(n-1)
        count+=1
    return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
    spf[1]=1
    for i in range(2,mx+1):
        if spf[i]==mx:
            spf[i]=i
            for j in range(i*i,mx+1,i):
                if i<spf[j]:
                    spf[j]=i
    return
def readTree(n,e): # to read tree
    adj=[set() for i in range(n+1)]
    for i in range(e):
        u1,u2=IP()
        adj[u1].add(u2)
    return adj
#####################################################################################
mod=10**9+7
def solve():
    n,m=IP()
    li=[]
    for i in range(n):
        temp=L()
        li.append(temp)
    ans=[[0 for j in range(m)] for i in range(n)]
    brk=False
    for i in range(n):
        for j in range(m):
            x=li[i][j]
            if ((j-1)>=0 and ans[i][j-1]==x) or ((i-1)>=0 and ans[i-1][j]==x):
                ans[i][j]=x+1
                x=ans[i][j]
                if ((j-1)>=0 and li[i][j-1]==x) or ((i-1)>=0 and li[i-1][j]==x):
                    brk=True
                    break
            else:
                ans[i][j]=li[i][j]
        if brk:
            break
    if brk:
        ans=[[0 for j in range(m)] for i in range(n)]
        for i in range(n-1,-1,-1):
            for j in range(m-1,-1,-1):
                x=li[i][j]
                if ((j+1)<m and ans[i][j+1]==x) or ((i+1)<n and ans[i+1][j]==x):
                    ans[i][j]=x+1
                else:
                    ans[i][j]=x
        for ele in ans:
            print(*ele)
    else:
        for ele in ans:
            print(*ele)
    return

t=II()
for i in range(t):
    solve()

    #######
   #
  #
 #######   #     #  # ####   # #     #
       #  # #   #  # #   #  # # #   #
      #  ####  #  # ####   ####  # #
######  #   # #### #    # #   #   #

# ``````¶0````1¶1_```````````````````````````````````````
# ```````¶¶¶0_`_¶¶¶0011100¶¶¶¶¶¶¶001_````````````````````
# ````````¶¶¶¶¶00¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0_````````````````
# `````1_``¶¶00¶0000000000000000000000¶¶¶¶0_`````````````
# `````_¶¶_`0¶000000000000000000000000000¶¶¶¶¶1``````````
# ```````¶¶¶00¶00000000000000000000000000000¶¶¶_`````````
# ````````_¶¶00000000000000000000¶¶00000000000¶¶`````````
# `````_0011¶¶¶¶¶000000000000¶¶00¶¶0¶¶00000000¶¶_````````
# ```````_¶¶¶¶¶¶¶00000000000¶¶¶¶0¶¶¶¶¶00000000¶¶1````````
# ``````````1¶¶¶¶¶000000¶¶0¶¶¶¶¶¶¶¶¶¶¶¶0000000¶¶¶````````
# ```````````¶¶¶0¶000¶00¶0¶¶`_____`__1¶0¶¶00¶00¶¶````````
# ```````````¶¶¶¶¶00¶00¶10¶0``_1111_`_¶¶0000¶0¶¶¶````````
# ``````````1¶¶¶¶¶00¶0¶¶_¶¶1`_¶_1_0_`1¶¶_0¶0¶¶0¶¶````````
# ````````1¶¶¶¶¶¶¶0¶¶0¶0_0¶``100111``_¶1_0¶0¶¶_1¶````````
# ```````1¶¶¶¶00¶¶¶¶¶¶¶010¶``1111111_0¶11¶¶¶¶¶_10````````
# ```````0¶¶¶¶__10¶¶¶¶¶100¶¶¶0111110¶¶¶1__¶¶¶¶`__````````
# ```````¶¶¶¶0`__0¶¶0¶¶_¶¶¶_11````_0¶¶0`_1¶¶¶¶```````````
# ```````¶¶¶00`__0¶¶_00`_0_``````````1_``¶0¶¶_```````````
# ``````1¶1``¶¶``1¶¶_11``````````````````¶`¶¶````````````
# ``````1_``¶0_¶1`0¶_`_``````````_``````1_`¶1````````````
# ``````````_`1¶00¶¶_````_````__`1`````__`_¶`````````````
# ````````````¶1`0¶¶_`````````_11_`````_``_``````````````
# `````````¶¶¶¶000¶¶_1```````_____```_1``````````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶0_``````_````_1111__``````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶01_`````_11____1111_```````````
# `````````¶¶0¶0¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1101_______11¶_```````````
# ``````_¶¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0¶0¶¶¶1````````````
# `````0¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1`````````````
# ````0¶0000000¶¶0_````_011_10¶110¶01_1¶¶¶0````_100¶001_`
# ```1¶0000000¶0_``__`````````_`````````0¶_``_00¶¶010¶001
# ```¶¶00000¶¶1``_01``_11____``1_``_`````¶¶0100¶1```_00¶1
# ``1¶¶00000¶_``_¶_`_101_``_`__````__````_0000001100¶¶¶0`
# ``¶¶¶0000¶1_`_¶``__0_``````_1````_1_````1¶¶¶0¶¶¶¶¶¶0```
# `_¶¶¶¶00¶0___01_10¶_``__````1`````11___`1¶¶¶01_````````
# `1¶¶¶¶¶0¶0`__01¶¶¶0````1_```11``___1_1__11¶000`````````
# `1¶¶¶¶¶¶¶1_1_01__`01```_1```_1__1_11___1_``00¶1````````
# ``¶¶¶¶¶¶¶0`__10__000````1____1____1___1_```10¶0_```````
# ``0¶¶¶¶¶¶¶1___0000000```11___1__`_0111_```000¶01```````
# ```¶¶¶00000¶¶¶¶¶¶¶¶¶01___1___00_1¶¶¶`_``1¶¶10¶¶0```````
# ```1010000¶000¶¶0100_11__1011000¶¶0¶1_10¶¶¶_0¶¶00``````
# 10¶000000000¶0________0¶000000¶¶0000¶¶¶¶000_0¶0¶00`````
# ¶¶¶¶¶¶0000¶¶¶¶_`___`_0¶¶¶¶¶¶¶00000000000000_0¶00¶01````
# ¶¶¶¶¶0¶¶¶¶¶¶¶¶¶_``_1¶¶¶00000000000000000000_0¶000¶01```
# 1__```1¶¶¶¶¶¶¶¶¶00¶¶¶¶00000000000000000000¶_0¶0000¶0_``
# ```````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000010¶00000¶¶_`
# ```````0¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000¶10¶¶0¶¶¶¶¶0`
# ````````¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000000010¶¶¶0011```
# ````````1¶¶¶¶¶¶¶¶¶¶0¶¶¶0000000000000000000¶100__1_`````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶000000000000000000¶11``_1``````
# `````````1¶¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000¶11___1_`````
# ``````````¶¶¶¶¶¶0¶0¶¶¶¶¶¶¶0000000000000000¶11__``1_````
# ``````````¶¶¶¶¶¶¶0¶¶¶0¶¶¶¶¶000000000000000¶1__````__```
# ``````````¶¶¶¶¶¶¶¶0¶¶¶¶¶¶¶¶¶0000000000000000__`````11``
# `````````_¶¶¶¶¶¶¶¶¶000¶¶¶¶¶¶¶¶000000000000011_``_1¶¶¶0`
# `````````_¶¶¶¶¶¶0¶¶000000¶¶¶¶¶¶¶000000000000100¶¶¶¶0_`_
# `````````1¶¶¶¶¶0¶¶¶000000000¶¶¶¶¶¶000000000¶00¶¶01`````
# `````````¶¶¶¶¶0¶0¶¶¶0000000000000¶0¶00000000011_``````_
# ````````1¶¶0¶¶¶0¶¶¶¶¶¶¶000000000000000000000¶11___11111
# ````````¶¶¶¶0¶¶¶¶¶00¶¶¶¶¶¶000000000000000000¶011111111_
# ```````_¶¶¶¶¶¶¶¶¶0000000¶0¶00000000000000000¶01_1111111
# ```````0¶¶¶¶¶¶¶¶¶000000000000000000000000000¶01___`````
# ```````¶¶¶¶¶¶0¶¶¶000000000000000000000000000¶01___1````
# ``````_¶¶¶¶¶¶¶¶¶00000000000000000000000000000011_111```
# ``````0¶¶0¶¶¶0¶¶0000000000000000000000000000¶01`1_11_``
# ``````¶¶¶¶¶¶0¶¶¶0000000000000000000000000000001`_0_11_`
# ``````¶¶¶¶¶¶¶¶¶00000000000000000000000000000¶01``_0_11`
# ``````¶¶¶¶0¶¶¶¶00000000000000000000000000000001```_1_11


import time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import deque
from collections import defaultdict
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
    return int(stdin.readline())
def IP(): # to take tuple as input
    return map(int,stdin.readline().split())
def L(): # to take list as input
    return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
    return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
    return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
    return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
    if a==0:
        return b
    elif b==0:
        return a
    if a>b:
        return gcd(a%b,b)
    else:
        return gcd(a,b%a)
def bfs(adj,v): # a schema of bfs
    visited=[False]*(v+1)
    q=deque()
    while q:
        pass
def sieve():
    li=[True]*(2*(10**5)+5)
    li[0],li[1]=False,False
    for i in range(2,len(li),1):
        if li[i]==True:
            for j in range(i*i,len(li),i):
                li[j]=False
    prime=[]
    for i in range((2*(10**5)+5)):
        if li[i]==True:
            prime.append(i)
    return prime
def setBit(n):
    count=0
    while n!=0:
        n=n&(n-1)
        count+=1
    return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
    spf[1]=1
    for i in range(2,mx+1):
        if spf[i]==mx:
            spf[i]=i
            for j in range(i*i,mx+1,i):
                if i<spf[j]:
                    spf[j]=i
    return
def readTree(n,e): # to read tree
    adj=[set() for i in range(n+1)]
    for i in range(e):
        u1,u2=IP()
        adj[u1].add(u2)
    return adj
#####################################################################################
mod=10**9+7
def solve():
    n,m=IP()
    li=[]
    for i in range(n):
        temp=L()
        li.append(temp)
    ans1=[[0 for j in range(m)] for i in range(n)]
    brk=False
    for i in range(n):
        for j in range(m):
            x=li[i][j]
            if ((j-1)>=0 and ans1[i][j-1]==x) or ((i-1)>=0 and ans1[i-1][j]==x):
                ans1[i][j]=x+1
                x=ans1[i][j]
                if ((j-1)>=0 and ans1[i][j-1]==x) or ((i-1)>=0 and ans1[i-1][j]==x):
                    brk=True
                    break
            else:
                ans1[i][j]=li[i][j]
        if brk:
            break
    if brk:
        brk=False
        ans2=[[0 for j in range(m)] for i in range(n)]
        for i in range(n-1,-1,-1):
            for j in range(m-1,-1,-1):
                x=li[i][j]
                if ((j+1)<m and ans2[i][j+1]==x) or ((i+1)<n and ans2[i+1][j]==x):
                    ans2[i][j]=x+1
                    x=ans2[i][j]
                    if ((j+1)<m and ans2[i][j+1]==x) or ((i+1)<n and ans2[i+1][j]==x):
                        brk=True
                        break
                else:
                    ans2[i][j]=x
            if brk:
                break
        if brk:
            brk=False
            ans3=[[0 for j in range(m)] for i in range(n)]
            for i in range(n):
                for j in range(m-1,-1,-1):
                    x=li[i][j]
                    if ((j+1)<m and ans3[i][j+1]==x) or ((i-1)>=0 and ans3[i-1][j]==x):
                        ans3[i][j]=x+1
                        x=ans3[i][j]
                        if ((j+1)<m and ans3[i][j+1]==x) or ((i-1)>=0 and ans3[i-1][j]==x):
                            brk=True
                            break
                    else:
                        ans3[i][j]=x
                if brk:
                    break
            if brk:
                brk=False
                ans4=[[0 for j in range(m)] for i in range(n)]
                for i in range(n-1,-1,-1):
                    for j in range(m):
                        x=li[i][j]
                        if ((j-1)>=0 and ans4[i][j-1]==x) or ((i+1)<n and ans4[i+1][j]==x):
                            ans4[i][j]=x+1
                            x=ans4[i][j]
                            if ((j-1)>=0 and ans4[i][j-1]==x) or ((i+1)<n and ans4[i+1][j]==x):
                                brk=True
                                break
                        else:
                            ans4[i][j]=x
                    if brk:
                        break
                if brk:
                    return
                else:
                    for ele in ans4:
                        print(*ele)
                    return
            else:
                for ele in ans3:
                    print(*ele)
                return
        else:
            for ele in ans2:
                print(*ele)
            return
    else:
        for ele in ans1:
            print(*ele)
        return

t=II()
for i in range(t):
    solve()

    #######
   #
  #
 #######   #     #  # ####   # #     #
       #  # #   #  # #   #  # # #   #
      #  ####  #  # ####   ####  # #
######  #   # #### #    # #   #   #

# ``````¶0````1¶1_```````````````````````````````````````
# ```````¶¶¶0_`_¶¶¶0011100¶¶¶¶¶¶¶001_````````````````````
# ````````¶¶¶¶¶00¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0_````````````````
# `````1_``¶¶00¶0000000000000000000000¶¶¶¶0_`````````````
# `````_¶¶_`0¶000000000000000000000000000¶¶¶¶¶1``````````
# ```````¶¶¶00¶00000000000000000000000000000¶¶¶_`````````
# ````````_¶¶00000000000000000000¶¶00000000000¶¶`````````
# `````_0011¶¶¶¶¶000000000000¶¶00¶¶0¶¶00000000¶¶_````````
# ```````_¶¶¶¶¶¶¶00000000000¶¶¶¶0¶¶¶¶¶00000000¶¶1````````
# ``````````1¶¶¶¶¶000000¶¶0¶¶¶¶¶¶¶¶¶¶¶¶0000000¶¶¶````````
# ```````````¶¶¶0¶000¶00¶0¶¶`_____`__1¶0¶¶00¶00¶¶````````
# ```````````¶¶¶¶¶00¶00¶10¶0``_1111_`_¶¶0000¶0¶¶¶````````
# ``````````1¶¶¶¶¶00¶0¶¶_¶¶1`_¶_1_0_`1¶¶_0¶0¶¶0¶¶````````
# ````````1¶¶¶¶¶¶¶0¶¶0¶0_0¶``100111``_¶1_0¶0¶¶_1¶````````
# ```````1¶¶¶¶00¶¶¶¶¶¶¶010¶``1111111_0¶11¶¶¶¶¶_10````````
# ```````0¶¶¶¶__10¶¶¶¶¶100¶¶¶0111110¶¶¶1__¶¶¶¶`__````````
# ```````¶¶¶¶0`__0¶¶0¶¶_¶¶¶_11````_0¶¶0`_1¶¶¶¶```````````
# ```````¶¶¶00`__0¶¶_00`_0_``````````1_``¶0¶¶_```````````
# ``````1¶1``¶¶``1¶¶_11``````````````````¶`¶¶````````````
# ``````1_``¶0_¶1`0¶_`_``````````_``````1_`¶1````````````
# ``````````_`1¶00¶¶_````_````__`1`````__`_¶`````````````
# ````````````¶1`0¶¶_`````````_11_`````_``_``````````````
# `````````¶¶¶¶000¶¶_1```````_____```_1``````````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶0_``````_````_1111__``````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶01_`````_11____1111_```````````
# `````````¶¶0¶0¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1101_______11¶_```````````
# ``````_¶¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0¶0¶¶¶1````````````
# `````0¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1`````````````
# ````0¶0000000¶¶0_````_011_10¶110¶01_1¶¶¶0````_100¶001_`
# ```1¶0000000¶0_``__`````````_`````````0¶_``_00¶¶010¶001
# ```¶¶00000¶¶1``_01``_11____``1_``_`````¶¶0100¶1```_00¶1
# ``1¶¶00000¶_``_¶_`_101_``_`__````__````_0000001100¶¶¶0`
# ``¶¶¶0000¶1_`_¶``__0_``````_1````_1_````1¶¶¶0¶¶¶¶¶¶0```
# `_¶¶¶¶00¶0___01_10¶_``__````1`````11___`1¶¶¶01_````````
# `1¶¶¶¶¶0¶0`__01¶¶¶0````1_```11``___1_1__11¶000`````````
# `1¶¶¶¶¶¶¶1_1_01__`01```_1```_1__1_11___1_``00¶1````````
# ``¶¶¶¶¶¶¶0`__10__000````1____1____1___1_```10¶0_```````
# ``0¶¶¶¶¶¶¶1___0000000```11___1__`_0111_```000¶01```````
# ```¶¶¶00000¶¶¶¶¶¶¶¶¶01___1___00_1¶¶¶`_``1¶¶10¶¶0```````
# ```1010000¶000¶¶0100_11__1011000¶¶0¶1_10¶¶¶_0¶¶00``````
# 10¶000000000¶0________0¶000000¶¶0000¶¶¶¶000_0¶0¶00`````
# ¶¶¶¶¶¶0000¶¶¶¶_`___`_0¶¶¶¶¶¶¶00000000000000_0¶00¶01````
# ¶¶¶¶¶0¶¶¶¶¶¶¶¶¶_``_1¶¶¶00000000000000000000_0¶000¶01```
# 1__```1¶¶¶¶¶¶¶¶¶00¶¶¶¶00000000000000000000¶_0¶0000¶0_``
# ```````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000010¶00000¶¶_`
# ```````0¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000¶10¶¶0¶¶¶¶¶0`
# ````````¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000000010¶¶¶0011```
# ````````1¶¶¶¶¶¶¶¶¶¶0¶¶¶0000000000000000000¶100__1_`````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶000000000000000000¶11``_1``````
# `````````1¶¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000¶11___1_`````
# ``````````¶¶¶¶¶¶0¶0¶¶¶¶¶¶¶0000000000000000¶11__``1_````
# ``````````¶¶¶¶¶¶¶0¶¶¶0¶¶¶¶¶000000000000000¶1__````__```
# ``````````¶¶¶¶¶¶¶¶0¶¶¶¶¶¶¶¶¶0000000000000000__`````11``
# `````````_¶¶¶¶¶¶¶¶¶000¶¶¶¶¶¶¶¶000000000000011_``_1¶¶¶0`
# `````````_¶¶¶¶¶¶0¶¶000000¶¶¶¶¶¶¶000000000000100¶¶¶¶0_`_
# `````````1¶¶¶¶¶0¶¶¶000000000¶¶¶¶¶¶000000000¶00¶¶01`````
# `````````¶¶¶¶¶0¶0¶¶¶0000000000000¶0¶00000000011_``````_
# ````````1¶¶0¶¶¶0¶¶¶¶¶¶¶000000000000000000000¶11___11111
# ````````¶¶¶¶0¶¶¶¶¶00¶¶¶¶¶¶000000000000000000¶011111111_
# ```````_¶¶¶¶¶¶¶¶¶0000000¶0¶00000000000000000¶01_1111111
# ```````0¶¶¶¶¶¶¶¶¶000000000000000000000000000¶01___`````
# ```````¶¶¶¶¶¶0¶¶¶000000000000000000000000000¶01___1````
# ``````_¶¶¶¶¶¶¶¶¶00000000000000000000000000000011_111```
# ``````0¶¶0¶¶¶0¶¶0000000000000000000000000000¶01`1_11_``
# ``````¶¶¶¶¶¶0¶¶¶0000000000000000000000000000001`_0_11_`
# ``````¶¶¶¶¶¶¶¶¶00000000000000000000000000000¶01``_0_11`
# ``````¶¶¶¶0¶¶¶¶00000000000000000000000000000001```_1_11


import sys, os
# import numpy as np
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
# read_f = lambda file:  list(map(int, file.readline().strip().split()))
# from time import time
# sys.setrecursionlimit(5*10**6)

MOD = 10**9 + 7

def main():
	# file1 = open("C:\\Users\\shank\\Desktop\\Comp_Code\\input.txt", "r")
	# n = int(file1.readline().strip());
	# arr = list(map(int, file1.read().strip().split(" ")))
	# file1.close()
	for _ in range(int(input())):
		n, m = read(); mat = []
		for i in range(n):mat.append(read())

		last = 0
		for i in range(n):
			last ^= (m%2 == 0)
			for j in range(m):
				mat[i][j] += (last != mat[i][j]%2 )
				last ^= 1
				print(i, j , last)

		for i in mat:print(*i)

	# file = open("output.txt", "w")
	# file.write(ans+"\n")
	# file.close()

if __name__ == "__main__":
	main()

"""

2 3 4 2
1 4 3 2
1 4 3 1

"""


import sys, os
# import numpy as np
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
# read_f = lambda file:  list(map(int, file.readline().strip().split()))
# from time import time
# sys.setrecursionlimit(5*10**6)

MOD = 10**9 + 7

def main():
	# file1 = open("C:\\Users\\shank\\Desktop\\Comp_Code\\input.txt", "r")
	# n = int(file1.readline().strip());
	# arr = list(map(int, file1.read().strip().split(" ")))
	# file1.close()
	for _ in range(int(input())):
		n, m = read(); mat = []
		for i in range(n):mat.append(read())

		last = 0
		for i in range(n):
			last ^= (m%2 == 0)
			for j in range(m):
				mat[i][j] += (last != mat[i][j]%2 )
				last ^= 1
				# print(i, j , last)

		for i in mat:print(*i)

	# file = open("output.txt", "w")
	# file.write(ans+"\n")
	# file.close()

if __name__ == "__main__":
	main()

"""

2 3 4 2
1 4 3 2
1 4 3 1

"""


import sys, os
# import numpy as np
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
# read_f = lambda file:  list(map(int, file.readline().strip().split()))
# from time import time
# sys.setrecursionlimit(5*10**6)

MOD = 10**9 + 7

def main():
	# file1 = open("C:\\Users\\shank\\Desktop\\Comp_Code\\input.txt", "r")
	# n = int(file1.readline().strip());
	# arr = list(map(int, file1.read().strip().split(" ")))
	# file1.close()
	for _ in range(int(input())):
		n, m = read(); mat = []
		for i in range(n):mat.append(read())

		for i in range(n):
			for j in range(m):
				mat[i][j] += (((i*m + j)+(i%2))%2 != mat[i][j]%2 )

		for i in mat:print(*i)

	# file = open("output.txt", "w")
	# file.write(ans+"\n")
	# file.close()

if __name__ == "__main__":
	main()

"""

2 3 4 2
1 4 3 2
1 4 3 1

"""


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v,visi):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    # visi = {}
    visi[i*n +j] = True
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1
        curr = v[p][q]
        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]
    visi = {}
    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if ((i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr)) and \
            not visi.get(i*n +j,False):
                bfs(i,j,n,m,v,visi)

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    visi = {}
    visi[i*n +j] = True
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1
        curr = v[p][q]
        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]

    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if (i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr):
                bfs(i,j,n,m,v)

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v,visi):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    # visi = {}
    visi[i*n +j] = True
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1
        curr = v[p][q]
        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]
    visi = {}
    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if ((i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr)) and not visi.get(i*n +j,False):
                bfs(i,j,n,m,v,visi)

    for row in v:
        print(*row)

    t -= 1


t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]
    #visi = {}
    for i in range(n):
        for j in range(m):
            # curr = v[i][j]
            # if ((i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or
            # (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr)) and not visi.get(i*n +j,False):
            #     bfs(i,j,n,m,v,visi)
            if (i+j)%2 == 0 and v[i][j]%2 != 0:
                v[i][j] += 1
            elif (i+j)%2 != 0 and v[i][j]%2 == 0:
                v[i][j] += 1

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    visi = {}
    visi[p*n +q] = True
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1
        curr = v[p][q]
        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]

    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if (i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr):
                bfs(i,j,n,m,v)

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    visi = {}
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1

        if (p-1 >= 0 and v[p-1][q] == curr) and not visi[(p-1)*n +q]:
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi[(p+1)*n +q]:
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi[(p)*n +q-1]:
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi[(p)*n +q+1]:
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]

    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if (i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr):
                bfs(i,j,n,m,v)

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    visi = {}
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1

        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]

    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if (i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr):
                bfs(i,j,n,m,v)

    for row in v:
        print(*row)

    t -= 1


# n = int(input().strip())
# v = list(map(int, input().strip().split()))
# a = sorted(v)

from collections import deque

def bfs(i,j,n,m,v):
    v[i][j] += 1
    que = deque([])
    curr = v[i][j]
    visi = {}
    visi[p*n +q] = True
    if (i-1 >= 0 and v[i-1][j] == curr):
        que.append((i-1,j))
        visi[(i-1)*n +j] = True

    if (i+1 < n and v[i+1][j] == curr):
        que.append((i+1,j))
        visi[(i+1)*n +j] = True

    if (j-1 >= 0 and v[i][j-1] == curr):
        que.append((i,j-1))
        visi[(i)*n +j-1] = True

    if (j+1 <m and v[i][j+1] == curr):
        que.append((i,j+1))
        visi[(i)*n +j+1] = True

    while len(que):
        p,q = que.popleft()
        v[p][q] += 1
        if (p-1 >= 0 and v[p-1][q] == curr) and not visi.get((p-1)*n +q,False):
            que.append((p-1,q))
            visi[(p-1)*n +q] = True

        if (p+1 < n and v[p+1][q] == curr) and not visi.get((p+1)*n +q,False):
            que.append((p+1,q))
            visi[(p+1)*n +q] = True

        if (q-1 >= 0 and v[p][q-1] == curr) and not visi.get((p)*n +q-1,False):
            que.append((p,q-1))
            visi[(p)*n +q-1] = True

        if (q+1 <m and v[p][q+1] == curr) and not visi.get((p)*n +q+1,False):
            que.append((p,q+1))
            visi[(p)*n +q+1] = True

t = int(input().strip())
while(t):
    n,m = map(int, input().strip().split())
    v = [list(map(int, input().strip().split())) for i in range(n)]

    for i in range(n):
        for j in range(m):
            curr = v[i][j]
            if (i-1 >= 0 and v[i-1][j] == curr) or (i+1 < n and v[i+1][j] == curr) or \
            (j-1 >= 0 and v[i][j-1] == curr) or (j+1 <m and v[i][j+1] == curr):
                bfs(i,j,n,m,v)

    for row in v:
        print(*row)

    t -= 1


import sys
input = sys.stdin.readline

def prog():
    for _ in range(int(input())):
        n,m = map(int(input().split()))
        a = [list(map(int,input().split())) for i in range(n)]

        for i in range(n):
            for j in range(m):
                 a[i][j] += ((i+j)%2 != a[i][j] % 2)

        for row in a:
            print(*row)
prog()


import sys
input = sys.stdin.readline

def prog():
    for _ in range(int(input())):
        n,m = map(int,input().split())
        a = [list(map(int,input().split())) for i in range(n)]

        for i in range(n):
            for j in range(m):
                 a[i][j] += ((i+j)%2 != a[i][j] % 2)

        for row in a:
            print(*row)
prog()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    t=int(input())
    for _ in range(t):
        n,m=map(int,input().split(" "))
        mat=[list(map(int,input().split(" "))) for x in range(n)]
        for x in range(n):
            for y in range(m):
                if (x+y)%2!=mat[x][y]%2:
                    mat[x][y]+=1
        for x in mat:
            print(*x)

#-----------------------------BOSS-------------------------------------!
# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


for _ in range(int(input())):
    n,m = map(int,input().split())
    a = []
    for i in range(n):
        a.append(list(map(int,input().split())))
    for i in range(n):
        for j in range(m):
            if a[i][j]&1 != (i+j)&1:
                a[i][j] += 1
    for i in range(n):
        print(*a[i])


for _ in range(int(input())):
    n,m = map(int,input().split())
    a = []
    for i in range(n):
        a.append(list(map(int,input().split()))
    for i in range(n):
        for j in range(m):
            if a[i][j]&1 != (i+j)&1:
                a[i][j] += 1
    for i in range(n):
        print(*a[i])


import sys
input = sys.stdin.readline
from collections import *

t = int(input())

for _ in range(t):
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(n)]
    idx = defaultdict(list)

    for i in range(n):
        for j in range(m):
            idx[a[i][j]].append((i, j))

    for k in sorted(idx.keys()):
        for i, j in idx[k]:
            for ni, nj in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if 0<=ni<n and 0<nj<m and a[i][j]==a[ni][nj]:
                    a[i][j] += 1
                    break

    for ai in a:
        print(*ai)


import sys
input = sys.stdin.readline
from collections import *

t = int(input())

for _ in range(t):
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(n)]

    for i in range(n):
        for j in range(m):
            if (i+j)%2==0 and a[i][j]%2==1:
                a[i][j] += 1
            elif (i+j)%2==1 and a[i][j]%2==0:
                a[i][j] += 1

    for ai in a:
        print(*ai)


for __ in range(int(input())):
    n, m = list(map(int, input().split()))
    ar = []
    for i in range(n):
        ar.append(list(map(int, input().split())))
    for i in range(n):
        for j in range(n):
            if (i + j) % 2  != ar[i][j]:
                ar[i][j] += 1
    for elem in ar:
        print(*elem)


for __ in range(int(input())):
    n, m = list(map(int, input().split()))
    ar = []
    for i in range(n):
        ar.append(list(map(int, input().split())))
    for i in range(n):
        for j in range(m):
            if (i + j) % 2 != ar[i][j] % 2:
                ar[i][j] += 1
    for elem in ar:
        print(*elem)


#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading

#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now-----------------------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
#-------------------------------------------------------------------------
mod=10**9+7
for _ in range (int(input())):
    n,m=map(int,input().split())
    a=list()
    for i in range (n):
        b=list(map(int,input().split()))
        a.append(b)
    p=0
    for i in range (n):
        p=1-p
        q=p
        for j in range (m):
            if a[i][j]%2!=q:
                a[i][j]+=1
            q=1-q
    for i in range (n):
        print(*a[i])