module main; // https://yukicoder.me/problems/no/307/editorial より // 2次元グリッド、幅優先探索 import std; int H, W; int[][] A; int n0, n1; // 色0と色1の数 void fill(int r, int c, int color) { A[r][c] = color; if (color == 0) { n0++; n1--; } else { n0--; n1++; } if (0 < r && A[r - 1][c] != color) fill(r - 1, c, color); if (r < H - 1 && A[r + 1][c] != color) fill(r + 1, c, color); if (0 < c && A[r][c - 1] != color) fill(r, c - 1, color); if (c < W - 1 && A[r][c + 1] != color) fill(r, c + 1, color); } void main() { // 入力 readln.chomp.formattedRead("%d %d", H, W); A = new int[][](H); foreach (ref a; A) { a = readln.split.to!(int[]); int n = a.count(0).to!int; n0 += n; n1 += W - n; } // クエリの処理 int Q = readln.chomp.to!int; auto query = new int[][](Q); foreach (ref q; query) q = readln.split.to!(int[]); foreach (q; query) { int r = q[0] - 1, c = q[1] - 1, x = q[2]; if (A[r][c] == x) continue; fill (r, c, x); if (n0 == H * W || n1 == H * W) { // 全部同じ色になったら最後のクエリの色で塗りつぶして答えを出力 foreach (ref a; A) a[] = query[Q - 1][2]; break; } } // 答えの出力 writefln("%(%(%d %)\n%)", A); }