You’re given a cake in a form of the N \times M matrix. Each cell of the cake can be either red or green. The cake is considered correct if any two adjacent cells of the matrix are different. You can change any green cell of the given cake to red in 3 units of penalty and red to green in 5 units. Determine the minimum penalty you need to make your cake correct.
Notice there are only two different correct cakes. Try each one and choose the one with the minimum penalty.
Look at the top left cherry. It can be either red or green. If the color of the top left cherry is determined then it is easy to see the first row of the cake is determined uniquely, or more precisely, two adjacent cherries have different colors. Again, if the cherries of the first row are determined, then the second row is also uniquely determined. Moreover, if the cherry in a certain column of the first row is determined, then the cherry in the same column of the second row has a color different from the color of the cherry in the first row. In the same way, the remaining rows of the cake can be uniquely restored.
Therefore, there are only two different correct cakes: the first one with a green top left cherry and the second one with a red top left cherry. Try each one, count the penalty required and choose the best one.
The implementation itself is not hard. Firstly, read the input cake as two-dimensional array of characters. Create another one such array and fill it in the next way. Set its top left cell as green, for example. After that, fill the remaining characters of the first line in such a way that each two adjacent cherries are different. In the similar way, fill the remaining rows of the cake, with the cherry in the first column different from the cherry in the row above. Set variable for penalty and initialize it as zero. Then go over each cell of the created cake and check whether the corresponding cell of the input cake has different color. If so, add 3 or 5 to the penalty depending whether the input cell is green or red respectively. Do the same one more time, setting the top left cell as red.
There is a shorter implementation without creating any extra matrixes, but using the parity of the cell’s row and column sum.
Total time and memory complexity: O(NM).