#include using namespace std; class union_find { int n; int cnt; // number of connected components vector par; vector rank; vector sz; // size of each component public: union_find(int n) : n(n), cnt(n), par(n), rank(n), sz(n) { for (int i = 0; i < n; i++) { par[i] = i; sz[i] = 1; } } int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; --cnt; if (rank[x] < rank[y]) { par[x] = y; sz[y] += sz[x]; } else { par[y] = x; sz[x] += sz[y]; if (rank[x] == rank[y]) ++rank[x]; } } bool same(int x, int y) { return find(x) == find(y); } int compCnt() { return cnt; } int size(int x) { return sz[find(x)]; } }; int dy[] = {0, 1, 0, -1}; int dx[] = {1, 0, -1, 0}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int r, c; cin >> r >> c; vector > bd(r, vector(c)); for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) cin >> bd[i][j]; union_find tree(r * c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { for (int k = 0; k < 4; k++) { int it = i + dy[k]; int jt = j + dx[k]; if (0 <= it && it < r && 0 <= jt && jt < c) { if (bd[i][j] == bd[it][jt]) { tree.unite(i * c + j, it * c + jt); } } } } } int q; cin >> q; vector xs(q), ys(q), zs(q); for (int t = 0; t < q; t++) cin >> ys[t] >> xs[t] >> zs[t]; for (int t = 0; t < q; t++) { int y = ys[t] - 1; int x = xs[t] - 1; int z = zs[t]; int root = tree.find(y * c + x); if (bd[root/c][root%c] == z) continue; set added; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (!tree.same(root, i * c + j)) continue; for (int k = 0; k < 4; k++) { int it = i + dy[k]; int jt = j + dx[k]; if (0 <= it && it < r && 0 <= jt && jt < c) { if (!tree.same(root, it * c + jt)) { added.insert(it * c + jt); } } } } } for (int a: added) tree.unite(root, a); root = tree.find(root); bd[root/c][root%c] = z; if (tree.compCnt() == 1) break; } if (tree.compCnt() == 1) { int root = tree.find(0); bd[root/c][root%c] = zs.back(); } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { int root = tree.find(i * c + j); cout << bd[root/c][root%c] << " "; } cout << endl; } return 0; }