#include #define rep(i,n) for(int (i)=0;(i)<(n);(i)++) using namespace std; const int vmax=50010; int p[vmax]; void init(){rep(i,vmax) p[i]=i;} int find(int x){return x==p[x]?x:p[x]=find(p[x]);} void unite(int a,int b){a=find(a),b=find(b);p[b]=a;return;} bool same(int a,int b){return find(a)==find(b);} int h,w; int a[vmax]; int di[4]={1,0,-1,0},dj[4]={0,1,0,-1}; set neighbor[vmax]; int main(void){ init(); scanf("%d %d",&h,&w); rep(i,h)rep(j,w) scanf("%d",a+w*i+j); rep(i,h)rep(j,w){ int idx=w*i+j; rep(k,4){ int ni=i,nj=j; ni+=di[k],nj+=dj[k]; if(ni<0||h<=ni) continue; if(nj<0||w<=nj) continue; int nidx=w*ni+nj; if(a[idx]==a[nidx]) unite(idx,nidx); } } rep(i,h)rep(j,w){ int idx=find(w*i+j); rep(k,4){ int ni=i,nj=j; ni+=di[k],nj+=dj[k]; if(ni<0||h<=ni) continue; if(nj<0||w<=nj) continue; int nidx=find(w*ni+nj); if(a[idx]!=a[nidx]) neighbor[idx].insert(nidx); } } int q; scanf("%d",&q); rep(loop,q){ int r,c,x; scanf("%d %d %d",&r,&c,&x); r--,c--; int idx=find(w*r+c); if(a[idx]==x) continue; a[idx]=x; set tmp; for(auto &nidx:neighbor[idx]){ unite(idx,nidx); for(auto &j:neighbor[nidx]) tmp.insert(j); } neighbor[idx]=tmp; } rep(i,h){ rep(j,w) printf("%s%d",(j?" ":""),a[find(w*i+j)]); puts(""); } return 0; }