Editorial for BSSPC '21 J3 - Magic Paint Gun Cartridges
Submitting an official solution before solving the problem yourself is a bannable offence.
The idea is to keep track of which cells need which color. This can be found by using the table given in the problem.
First, find which primary colors each cell needs. For example, an orange cell would need red and yellow.
Then, if the cell requires a certain primary color, increment the counter for that primary color if the previous cell in the same row did not require that primary color or if it is the first cell in that row.
Time Complexity: ~\mathcal O(NM)~