import std.stdio; import std.array; import std.string; import std.conv; import std.algorithm; import std.typecons; import std.range; import std.random; import std.math; import std.container; int H, W; int[][] B; int[4] dx = [0, 0, -1, 1]; int[4] dy = [-1, 1, 0, 0]; void dfs(int srow, int scol, int color) { if (color == B[srow][scol]) return; DList!(Tuple!(int, int)) stack; stack.insert(tuple(srow, scol)); bool[int][int] visited; int nr, nc; while (!stack.empty) { auto node = stack.front; stack.removeFront(); if (node[0] in visited && node[1] in visited[node[0]]) continue; visited[node[0]][node[1]] = true; B[node[0]][node[1]] = color; foreach (i; iota(4)) { nr = node[0] + dx[i]; nc = node[1] + dy[i]; if (nr < 0 || nr >= H || nc < 0 || nc >= W) continue; if (nr in visited && nc in visited[nr]) continue; if (B[nr][nc] == color) continue; stack.insert(tuple(nr, nc)); } } } void main() { auto input = readln.split.map!(to!int); H = input[0]; W = input[1]; B = new int[][](H, W); foreach (i; iota(H)) B[i] = readln.split.map!(to!int).array; int Q = readln.chomp.to!int; if (Q > 2000) { int c; foreach (i; iota(Q)) { auto q = readln.split.map!(to!int); c = q[2]; } foreach (i; iota(H)) foreach (j; iota(W)) B[i][j] = c; } else{ foreach (i; iota(Q)) { auto queries = readln.split.map!(to!int); dfs(queries[0]-1, queries[1]-1, queries[2]); } } foreach (i; iota(H)) writeln(B[i].map!(a => a.to!string).join(" ")); }