Problem Description
Given an m x n grid, perform the minimum number of operations so that for every cell grid[i][j]:
- It is equal to the cell below it (if exists): grid[i][j] == grid[i+1][j].
- It is different from the cell to its right (if exists): grid[i][j] != grid[i][j+1].
In one operation, you can change any cell's value to any non-negative number.
Key Insights
- The vertical equality condition implies that every cell in a column must be set to the same value.
- The horizontal distinctness condition forces the values chosen for adjacent columns to be different.
- Precompute the cost to change each column to a constant candidate value (0-9) by counting mismatches.
- Use dynamic programming over the columns where the state tracks the chosen candidate value for the current column.
- Only transitions between different candidate values are allowed between adjacent columns.
- The final answer is the minimum total cost after processing all columns.
Space and Time Complexity
Time Complexity: O(m * n * C + n * C^2), where C is the range of candidate values (C = 10, a constant).
Space Complexity: O(n * C) for the dynamic programming table.
Solution
The solution is broken into two primary steps:
- Precompute Cost Per Column: For every column and for each candidate value (0-9), calculate the number of operations (mismatches) to convert that column into all the same candidate value.
- Dynamic Programming: Define a DP table dp[col][candidate] representing the minimum operations needed for the first col+1 columns if the col-th column is set to candidate. The recurrence is based on the fact that adjacent columns must have different candidate values. Update the DP table accordingly and use the computed costs. This method reduces the 2D grid problem into a per-column cost problem and leverages a limited candidate set (0-9), which keeps the state space small.