Following should give you an idea.
If you start from the right bottom corner and traverse the matrix backwards, you can get the number of 'moves'.
Lets call move(r,c)
as pressing the button at r,c
.
So for example, if the N-1,M-1
entry is a zero, then you will have to press a button at N-1,M-1
. Subsequently all entries before it shall get toggled.
Now you check this for each entry in the last row backwards. Subsequently check this for each entry in the last column backwards.
Instead of actually toggling all the entries, you can keep a count for the number of times a 'column' is toggled while traversing a row and the number of times a row is toggled while traversing a column.
Now decrease N by 1 and M by 1 and repeat. The present value of each entry shall be:
Original value ^ number of times its column has been toggled ^ number of times its row has been toggled
& 1.