#pragma GCC optimize("Ofast") #include #include #include using namespace std; using namespace __gnu_pbds; using ll = long long; using ull = unsigned long long; using pii = pair; using pll = pair; #define rep(i, n) for(int i = 0; i < (n); ++i) #define all(x) (x).begin(),(x).end() constexpr char ln = '\n'; //constexpr long long MOD = 1000000007; constexpr long long MOD = 998244353; template inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return true;} return false; } template inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return true;} return false; } inline int popcount(int x) {return __builtin_popcount(x);} inline int popcount(long long x) {return __builtin_popcountll(x);} void print() { cout << "\n"; } template void print(const T &x, const Args &... args) { cout << x << " "; print(args...); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct UnionFind { int N; vector node; UnionFind(){} UnionFind(int N) : N(N), node(N,-1) {} void init(int x) { node.assign(x,-1); N = x; } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) return false; if (node[x] > node[y]) swap(x,y); node[x] += node[y]; node[y] = x; N--; return true; } bool same(int x, int y) {return root(x) == root(y);} int root(int x) { if (node[x] < 0) return x; return node[x] = root(node[x]); } int size(int x) {return -node[root(x)];} int count() const {return N;} }; const int dx[4] = {-1,0,1,0}; const int dy[4] = {0,-1,0,1}; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int H,W; cin >> H >> W; vector> A(H, vector(W)); rep(i,H) rep(j,W) cin >> A[i][j]; int S = 0; rep(i,H) rep(j,W) S += A[i][j]; int Q; cin >> Q; int all = -1; queue que; while (Q--) { int h,w,c; cin >> h >> w >> c; if (~all) { all = c; continue; } --h; --w; if (A[h][w] == c) continue; if (!(S%(H*W))) { all = c; continue; } A[h][w] = c; S += c ? 1 : -1; que.emplace(h,w); while (!que.empty()) { auto[x,y] = que.front(); que.pop(); rep(k,4) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx < 0 or nx >= H or ny < 0 or ny >= W) continue; if (A[nx][ny]==c) continue; A[nx][ny] = c; S += c ? 1 : -1; que.emplace(nx,ny); } } } if (~all) { rep(i,H) { rep(j,W) cout << all << " "; cout << ln; } } else { rep(i,H) { rep(j,W) cout << A[i][j] << " "; cout << ln; } } }