#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);} struct UF{ //O(loga(n)) int n; int m; vi d, r; UF(int n) : n(n), m(n), d(n, -1), r(n, 0){}; 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(r[x] < r[y]) swap(x, y); else if(r[x] == r[y]) r[x]++; d[x] += d[y]; d[y] = x; --m; return true; } int size(int i){ return -d[root(i)]; } int size() { return m; } }; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; int main(){ cin.tie(0); ios::sync_with_stdio(false); int h, w; cin >> h >> w; vector s(h, vi(w)); rep(i, h) rep(j, w) cin >> s[i][j]; const int n = h * w; vector nxts(n); UF uf(n); vi d(n); rep(y, h) rep(x, w) { int i = y * w + x; d[i] = s[y][x]; rep(k, 4) { int nx = x + dx[k]; int ny = y + dy[k]; int j = ny * w + nx; if(nx < 0 || ny < 0 || ny >= h || nx >= w) continue; if(s[y][x] == s[ny][nx]) uf.unite(i, j); else nxts[i].emplace_back(j); } } rep(i, n) if(i != uf.root(i)) { int j = uf.root(i); for(auto&& nxt : nxts[i]) nxts[j].emplace_back(nxt); sort(all(nxts[j])); nxts[j].erase(unique(all(nxts[j])), nxts[j].end()); } int q; cin >> q; vi v; vi used(n); rep(_, q) { int y, x, c; cin >> y >> x >> c; --y; --x; int i = y * w + x; i = uf.root(i); if(d[i] == c || uf.size() == 1) continue; v.clear(); rep(i, n) used[i] = 0; for(auto&& _nxt: nxts[i]) { int nxt = uf.root(_nxt); if(uf.same(i, nxt) || d[nxt] != c) continue; uf.unite(i, nxt); for(auto&& _j: nxts[nxt]) { int j = uf.root(_j); if(used[j] || uf.same(i, j) || d[j] == c) continue; v.emplace_back(j); used[j] = 1; } } i = uf.root(i); nxts[i] = v; d[i] = c; } rep(y, h) rep(x, w) { int i = y * w + x; cout << d[uf.root(i)] << (x+1 == w ? '\n' : ' '); } return 0; }