Awkward Lights
Time limit1sMemory limit128 MB
Given a grid where toggling a switch flips lights at a fixed Manhattan distance, decide over GF(2) whether all lights can be turned off simultaneously.
- Level
Medium7 of 10
- Topics
- Math, Bit manipulation, Matrix, Brute force
- Solved
- No attempts yet
Problem
You are working as a night watchman in an office building. Your task is to check whether all the lights in the building are turned off after all the office workers have left. If any lights are still on, you must turn them off. This task is not as easy as it sounds because of the strange behavior of the building's lighting system, described below. An electrical engineer inspected the system carefully but could not determine the cause of this behavior, so for now you have no choice but to keep relying on it.
Each floor of the building is a grid of square rooms. Every room has one light and one toggle switch. A toggle switch has two positions, but they do not correspond to fixed ON/OFF states. When the toggle switch of a room is flipped to its other position, the ON/OFF state of that room's light is reversed, and so are the lights of all rooms at a certain Manhattan distance from that room. The Manhattan distance between the room at and the room at is .
For example, in a grid, if the toggle switch of the room at is flipped and the given Manhattan distance is two, then the lights of the rooms at , , , , , and , as well as at itself, are reversed, as shown in Figure D.1, where black and white squares represent ON and OFF lights.

Figure D.1: An example of the lighting system's behavior.
Your task is to write a program that determines whether all the lights on a floor can be turned off.
Input
The input is a sequence of datasets. Each dataset has the following format.
m n d
S11 S12 S13 ... S1m
S21 S22 S23 ... S2m
...
Sn1 Sn2 Sn3 ... Snm
The first line of a dataset contains three integers. and (, ) are the numbers of columns and rows of the grid, respectively. () is the Manhattan distance. The following lines each contain integers giving the initial ON/OFF states. Each (, ) is the initial state of the light in the room at : 0 for OFF and 1 for ON.
The end of the input is indicated by a line containing three zeros.
Output
For each dataset, output 1 if all the lights can be turned off, or 0 otherwise. Print the answer on its own line for each dataset.