Brothers
InterviewTime limit1sMemory limit128 MB
Given a grid of counties owned by heirs in a cycle, apply K simultaneous rounds where a cell switches to the previous heir if an orthogonal neighbor already has that heir, then print the grid.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation, Matrix, Array
- Solved
- No attempts yet
Problem
A great King ruled a kingdom shaped like a rectangle. Before he died, he divided the territory into a grid of small rectangular counties and distributed them among his sons.
The King did not know that his sons had a peculiar rivalry: heir hated heir , heir hated heir , and so on; the last heir, , hated heir . Each heir hated exactly one other heir and no one else, so in general heir hated heir .
When the King died, war broke out. Two counties are adjacent if they share a horizontal or vertical border. During an attack, a county conquers an adjacent county whenever the owner of hates the owner of , and the conquered county then belongs to the attacker. All attacks happen simultaneously, and one round of simultaneous attacks is called a battle.
Because the only heir who hates the owner of a county is heir , every county that is attacked is conquered by that same heir. Equivalently: in each battle, a county currently owned by becomes owned by if at least one of its orthogonal (up, down, left, right) neighbors is owned by ; otherwise it keeps owner .
Given the number of heirs, the initial land distribution, and the number of battles, determine the land distribution after all battles have taken place. For example, with three heirs () a single battle transforms the map according to the rule above.
Input
The input contains several test cases. The first line of a test case contains four integers , , and separated by single spaces: is the number of heirs (), and are the dimensions of the kingdom (), and is the number of battles (). Heirs are numbered from (the first heir) to (the last heir).
Each of the next lines contains integers separated by single spaces: is the initial owner of the county in row and column ().
The last test case is followed by a line containing four zeros separated by single spaces.
Output
For each test case, print lines with integers each, separated by single spaces, in the same format as the input, representing the land distribution after all battles.