colorTheGrid
that takes parameters m
, n
, i
, j
, cur
, and prev
representing the number of rows, number of columns, current row, current column, current column's color state, and previous column's color state, respectively.i
equals m
, recursively call colorTheGrid
for the next column.j
equals n
, return 1 as we have found a valid coloring.i
is 0) and the DP table has a stored result for the current state, return the stored result.k
, check if it is different from the color above (up
) and the color to the left (left
). If so, recursively call colorTheGrid
for the next cell with updated cur
.