K spirals walk outward with run lengths 1,1,2,2,... on an N by M grid; for each cell print the earliest step any spiral reached it, within a 10^100 step limit.
Medium6ImplementationSimulationMathArrayNo attempts yetTime limit1sMemory limit64 MBThere is a table with N rows and M columns. The table starts empty, and K spirals are placed on it. Each spiral starts moving from its own starting cell, turning either clockwise or counter-clockwise.
One spiral moves by the following rules.
All spirals move at the same time, and each of them advances one cell per step. A spiral sometimes leaves the table and comes back inside it later.
After exactly 10100 steps, the value of each cell is the number of the earliest step in which some spiral stood on that cell.

Image 1: a spiral moving counter-clockwise

Image 2: a spiral moving clockwise
The first line contains N, M (1≤N,M≤50) and K (1≤K≤N×M).
Each of the next K lines contains integers Xi, Yi and Ti (1≤Xi≤N, 1≤Yi≤M, 0≤Ti≤1). Xi and Yi are the row and the column of the starting cell of the i-th spiral. Ti=0 means clockwise and Ti=1 means counter-clockwise. No two spirals share a starting cell.
Print N lines with M numbers each, separated by single spaces. The j-th number on the i-th line is the value of the cell in row i and column j.
The third example is explained by the picture below.

To make the picture easier to read, the letter A is attached to the numbers left by the first spiral and the letter B to the numbers left by the second spiral. Only the first 20 steps of the first spiral and the first 21 steps of the second spiral are drawn. The gray cells are the cells of the table. The other cells lie outside the table and are drawn to show how the spirals move outside it.