import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); boolean[][] field = new boolean[h][w]; UnionFindTree uft = new UnionFindTree(h * w); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { field[i][j] = (sc.nextInt() == 1); uft.setColor(i * w + j, field[i][j]); if (j > 0) { if (field[i][j] == field[i][j - 1]) { uft.unite(i * w + j, i * w + j - 1); } } if (i > 0) { if (field[i][j] == field[i - 1][j]) { uft.unite(i * w + j, (i - 1) * w + j); } } } } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (j > 0) { uft.addNeighbour(i * w + j, i * w + j - 1); uft.addNeighbour(i * w + j - 1, i * w + j); } if (i > 0) { uft.addNeighbour(i * w + j, (i - 1) * w + j); uft.addNeighbour((i - 1) * w + j, i * w + j); } } } int q = sc.nextInt(); for (int i = 0; i < q; i++) { int r = sc.nextInt() - 1; int c = sc.nextInt() - 1; boolean color = (sc.nextInt() == 1); uft.uniteColor(r * w + c, color); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (j > 0) { sb.append(" "); } if (uft.getColor(i * w + j)) { sb.append("1"); } else { sb.append("0"); } } sb.append("\n"); } System.out.print(sb); } static class UnionFindTree { int[] paretns; ArrayList> neighbours; boolean[] colors; public UnionFindTree(int size) { paretns = new int[size]; neighbours = new ArrayList<>(); colors = new boolean[size]; for (int i = 0; i < size; i++) { paretns[i] = i; neighbours.add(new HashSet<>()); } } public int find(int x) { if (x == paretns[x]) { return x; } else { return paretns[x] = find(paretns[x]); } } public boolean same(int x, int y) { return find(x) == find(y); } public void addNeighbour(int x, int y) { int xx = find(x); int yy = find(y); if (xx == yy) { return; } neighbours.get(xx).add(yy); } public void unite(int x, int y) { int xx = find(x); int yy = find(y); if (xx == yy) { return; } for (int zz : neighbours.get(xx)) { addNeighbour(yy, zz); } paretns[xx] = yy; } public void setColor(int x, boolean c) { colors[find(x)] = c; } public boolean getColor(int x) { return colors[find(x)]; } public void uniteColor(int x, boolean c) { if (colors[find(x)] == c) { return; } colors[find(x)] = c; for (int y : neighbours.get(find(x))) { unite(x, y); } } } }