Represent each column by an -bit mask, using bit for white and bit for blue.
First retain only masks with no three equal consecutive bits. Let be this set and . Since , we have . For each column, a selected mask must also agree with all prepainted cells.
Only the last two columns are needed to check the horizontal condition. Let count valid paintings of the processed prefix whose last two column masks are . We may append mask exactly when, in every row, the corresponding three bits in are not all equal. Then add to , taking all values modulo .
If , simply count the allowed masks for the first column. Otherwise initialize the DP using all allowed pairs of masks for the first two columns, process subsequent columns, and sum all final states.
Building the vertical-valid masks takes time, checking compatibility with fixed cells takes time, and the DP takes time. Precomputing the transitions uses memory. Each addition combines two reduced residues, so it fits in a signed 32-bit integer.