#include using namespace std; #define rep(i,n) REP(i,0,n) #define REP(i,s,e) for(int i=(s); i<(int)(e); i++) #define repr(i, n) REPR(i, n, 0) #define REPR(i, s, e) for(int i=(int)(s-1); i>=(int)(e); i--) #define all(r) r.begin(),r.end() #define rall(r) r.rbegin(),r.rend() typedef long long ll; typedef vector vi; typedef vector vl; const ll INF = 1e18; const ll MOD = 1e9 + 7; template T chmax(T& a, const T& b){return a = (a > b ? a : b);} template T chmin(T& a, const T& b){return a = (a < b ? a : b);} #define DEBUG_MODE #ifdef DEBUG_MODE #define dump(x) cout << #x << " : " << x << " " #define dumpL(x) cout << #x << " : " << x << '\n' #define LINE cout << "line : " << __LINE__ << " " #define LINEL cout << "line : " << __LINE__ << '\n' #define dumpV(v) cout << #v << " : ["; for(auto& t : v) cout << t << ", "; cout<<"]" << " " #define dumpVL(v) cout << #v << " : ["; for(auto& t : v) cout << t << ", "; cout<<"]" << endl #define STOP assert(false) #else #define dump(x) #define dumpL(x) #define LINE #define LINEL #define dumpV(v) #define dumpVL(v) #define STOP assert(false) #endif #define mp make_pair namespace std { template ostream &operator <<(ostream& out, const pair& a) { out << '(' << a.fi << ", " << a.se << ')'; return out; } } struct UF{ //O(loga(n)) int n; int m; vi d, c; vector> st; UF(int n) : n(n), m(n), d(n, -1), c(n), st(n){}; int root(int i){ if(d[i] < 0) return i; return d[i] = root(d[i]); } bool same(int x, int y){ return root(x) == root(y); } bool unite(int x, int y){ x = root(x); y = root(y); if(x == y) return false; if(st[x].size() < st[y].size()) swap(x, y); d[x] += d[y]; d[y] = x; --m; while(st[y].size()) { auto it = st[y].begin(); if(root(*it) != x) st[x].insert(root(*it)); st[y].erase(it); } return true; } int size(int i){ return -d[root(i)]; } int size() { return m; } }; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, -1, 0, 1}; int main(){ cin.tie(0); ios::sync_with_stdio(false); int h, w; cin >> h >> w; UF uf(h*w); vector a(h, vi(w)); rep(i, h) rep(j, w) cin >> a[i][j]; rep(i, h) rep(j, w) { uf.c[i * w + j] = a[i][j]; rep(k, 4) { int y = i + dy[k]; int x = j + dx[k]; if(y < 0 || x < 0 || y >= h || x >= w) continue; int r1 = uf.root(i * w + j); int r2 = uf.root(y * w + x); if(a[i][j] == a[y][x]) { uf.unite(r1, r2); } else { uf.st[r1].insert(r2); uf.st[r2].insert(r1); } } } int q; cin >> q; rep(_, q) { int y, x, c; cin >> y >> x >> c; --y; --x; int r1 = uf.root(y * w + x); uf.c[r1] = c; { auto st = uf.st[r1]; for(auto&& r2: st) if(uf.c[r2] == c) { uf.unite(r1, r2); } } { auto st = uf.st[r1]; for(auto&& r2: st) if(uf.c[r2] == c) { uf.unite(r1, r2); } } } rep(i, h) rep(j, w) { cout << uf.c[(uf.root(i*w+j))] << (j+1 == (int)a[i].size() ? '\n' : ' '); } return 0; }