#include using namespace std; 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; int ones = 0; vector > bd(r, vector(c)); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> bd[i][j]; if (bd[i][j] == 1) ++ones; } } int q; cin >> q; int x, y, z; for (int t = 0; t < q; t++) { cin >> y >> x >> z; --x, --y; if (ones == r * c || ones == 0) continue; if (bd[y][x] == z) continue; int prv = bd[y][x]; queue > que; que.emplace(y, x); bd[y][x] = z; if (z == 1) ++ones; else --ones; while (!que.empty()) { int cy, cx; tie(cy, cx) = que.front(); que.pop(); for (int k = 0; k < 4; k++) { int ny = cy + dy[k]; int nx = cx + dx[k]; if (0 <= ny && ny < r && 0 <= nx && nx < c) if (bd[ny][nx] == prv) { que.emplace(ny, nx); bd[ny][nx] = z; if (z == 1) ++ones; else --ones; } } } } if (ones == r * c || ones == 0) { for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) bd[i][j] = z; } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << bd[i][j] << " "; cout << endl; } return 0; }