We are given a $n \times m$ rectangular matrix in which every cell there is a light bulb, together with the information whether the bulb is ON or OFF.
Now i am required to switch OFF all the bulbs but i can perform only one operation that is as follows:
- I can simultaneously flip all the bulbs from ON to OFF and vice versa in any submatrix.
I need to switch OFF all the bulbs in a minimum number of moves and tell the number of moves needed as well as the moves themselves. Is there an efficient algorithm for this?
EXAMPLE: Let us assume $n=2$ and $m=3$ .The initial grid is as follow if $0$ stands for OFF and $1$ for ON:
$$\begin{matrix}1 & 1 & 1 \\ 0 & 1 & 1 \end{matrix}$$
Now we can switch OFF all bulbs in 2 moves which are as follow :
Move 1: Flip bulbs in subarray from $(1,1)$ to $(1,1)$
Move 2: Flip bulbs in subarray from $(1,2)$ to $(2,3)$
I don't know of an efficient algorithm that produces the minimal number of moves, but there's an algorithm that gives pretty good results.
The algorithm is based on the following observation: From the original $m \times n$ matrix construct a derived matrix of size $m+1 \times n+1$ by considering all $2\times2$ submatrices of the original matrix (imagine a border of zeros around it) and marking $0$ if the $2 \times 2$ submatrix has an even number of $1$s and $1$ if it has an odd number of $1$s. Now in the derived matrix a move on the original matrix corresponds to a move that switches just the four corners of a rectangle.
This all is best explained by an example. For your original matrix $$\begin{matrix}1 & 1 & 1 \\ 0 & 1 & 1\end{matrix}$$ the derived matrix would be $$\begin{matrix}1 & 0 & 0 & 1 \\ 1 & 1 & 0 & 0 \\ 0 & 1 & 0 & 1\end{matrix}$$ After the first move it becomes $$\begin{matrix}1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0\end{matrix}$$ and after the second one it is cleared.
The algorithm then looks for rectangles in the derived matrix with as many corners $1$ as possible and removes them in a greedy fashion. This is not optimal, but leads to quite good results.
Note in particular, that it follows that we must make at least $u/4$ moves, where $u$ is the number of $1$s in the derived matrix.