Skip to main content

Dynamic Programming - Hard Level - Question 2

Dynamic Programming - Hard Level - Question 2


Leetcode 1931 Painting a Grid with Three Different Colors

You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.

Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7.

Constraints:

1 <= m <= 5

1 <= n <= 1000


Analysis:

One of the difficulties is how to define the state.

In the process of defining a state, we need to consider two questions:

1. is the state defined a full description of the problem asked?

2. how can we derive the transition formula from the previous calculated states?

For this question, it is a matrix, so a natural choice is to use the index i and j. But this is not enough, since at each position we have three choices, (and its color should be different from its neighbors). So a third parameter is needed, and we need to somehow memorize the color information of its neighbors.

To this question, a hint is that the value of m is very small, so we can use `bit-wise` trick to record the color information with a mask, and the base is 3 (since we have 3 different choices for each position: 0 is the first color, 1 is the second, and 2 is the third). And we only need to record the previous m positions, since all the previous ones before the previous n positions have no limit for the remaining states.

To sum up, we can define a state as f(i, j, k), where i and j are the indexes, and k is the color state of the previous m positions. For each position, there are 3 choices, so m positions have pow(3, n) choices in total. For each k, `the most significant bit` is the one from the current position.

To easier coding (or thinking), I decide to rotate the matrix by 90 degree, or swap the m and n. Then we can think about this question line by line (if no swap, it is column by column).

Let focus on the transition formula:

if j == 0

then all the previous n positions are on the previous row. The only position that cannot having the same color as the current position is the one on right top of the current one (i-1, j);

if j > 0

then all the previous n positions are on the both the current row & previous row. There are two positions that cannot have the same color as the current one: one is on the right top of the current one (i-1, j), and the other is the one on the left (i, j-1).

In both cases, if in the same row, no adjacent two position can have the same color.

If k is the color state for the previous n position, then c = k/pow(3, n-1) is the color of the current position, so the color of the position on the right top is:  r1 = (c+1)%3 and r2 = (c+2)%3. Thus the previous states are:   k1 = [k%pow(3, n-1)]*3 + r1, and k2 = [k%pow(3, n-1)]*3 + r2.

Thus, the transition formula are:

if k is not a valid state (no adjacent positions have the same color):

    f(i, j, k) = 0

if k is a valid state:

    if j == 0

        f(i, j, k) = f(i-1, n-1, k1) + f(i-1, n-1, k2)

    if j > 0

        f(i, j, k) = f(i, j-1, k1) + f(i, j-1, k2)

So the final description of the f(i, j, k) is the number of ways to paint to the position (i, j) with the color state of the last n positions as k.

So the total number of ways of painting from (0, 0) to a specific position(i, j) is:

sum(f(i, j, k), where k is from [0, pow(3, n)).

We still have one thing to do: initialization.

For the first row, we just need to consider the current row (since there is no previous rows). For position (i, j) or (0, j), we just need to consider k < pow(3, j+1) since there are only j+1 positions in the consideration. Once k is valid, then its value can be assigned as 1 (since that once f(0, j, k) is valid, then f(0, j-1, k%pow(3, j-1)) is also valid, and, f(0, j, k) = f(0, j-1, k%pow(3, j-1)) in this case).

To make a summary, the dp idea in this question is like a "sliding-window" dp

1. for the position in the first row, we just consider the positions on the left in the same row;

2. for other row, we need to consider the previous n positions.

See the code below:


class Solution {
public:
    int colorTheGrid(int m, int n) {
        long res = 0, mod = 1e9 + 7;
        if(m<n) return colorTheGrid(n, m);
        int t = pow(3, n);
        vector<vector<vector<long>>> dp(m, vector<vector<long>>(n, vector<long>(t, 0)));
        // this is needed, o/w will TLE
        vector<vector<int>> valid(n, vector<int>(t, 0));
        for(int j=0; j<n; ++j) {
            for(int k=0; k<t; ++k) {
                valid[j][k] = isValid(k, 1, j, n);
            }
        }
        for(int i=0; i<m; ++i) {
            for(int j=0; j<n; ++j) {
                for(int k=0; k<t; ++k) {
                    if(i==0) {
                        if(k<pow(3, j+1) && isValid(k, i, j, n)) {
                            dp[i][j][k] = 1;
                            // cout<<i<<" "<<j<<" "<<k<<" "<<dp[i][j][k]<<endl;
                        }
                        continue;
                    }
                    if(!valid[j][k]) continue;
                    int f1 = k/(t/3), v = k%(t/3), r1 = (f1+1)%3, r2 = (f1+2)%3;
                    if(j>0) dp[i][j][k] = (dp[i][j-1][v*3+r1] + dp[i][j-1][v*3+r2])%mod;
                    else dp[i][j][k] = (dp[i-1][n-1][v*3+r1] + dp[i-1][n-1][v*3+r2])%mod;
                    // cout<<i<<" "<<j<<" "<<k<<" "<<dp[i][j][k]<<endl;
                }
            }
        }
        for(int i=0; i<t; ++i) {
            res += dp[m-1][n-1][i];
            res %= mod;
        }
        return res;
    }
private:
    bool isValid(int k, int i, int j, int n) {
        vector<int> vs(n, 0);
        if(i==0) vs.resize(j+1);
        int len = vs.size(), n1 = j+1, n2 = len - n1; 
        for(int id=0; id<len; ++id) {
            vs[id] = k%3;
            k /= 3;
        }
        for(int id=0; id+1<n2; ++id) {
            if(vs[id] == vs[id+1]) return false;
        }
        for(int id=n2; id+1<len; ++id) {
            if(vs[id] == vs[id+1]) return false;
        } 
        return true;
    }
};


Upper Layer

Comments

Popular posts from this blog

Sweep Line

Sweep (or scanning) line algorithm is very efficient for some specific questions involving discrete intervals. The intervals could be the lasting time of events, or the width of a building or an abstract square, etc. In the scanning line algorithm, we usually need to distinguish the start and the end of an interval. After the labeling of the starts and ends, we can sort them together based on the values of the starts and ends. Thus, if there are N intervals in total, we will have 2*N data points (since each interval will contribute 2). The sorting becomes the most time-consuming step, which is O(2N*log(2N) ~ O(N*logN). After the sorting, we usually can run a linear sweep for all the data points. If the data point is labeled as a starting point, it means a new interval is in the processing; when an ending time is reached, it means one of the interval has ended. In such direct way, we can easily figure out how many intervals are in the processes. Other related information can also be obt...

Bit Manipulation - Example

  Leetcode 136 Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Constraints: 1 <= nums.length <= 3 * 10^4 -3 * 10^4 <= nums[i] <= 3 * 10^4 Each element in the array appears twice except for one element which appears only once. Analysis: If there is no space limitation, this question can be solved by counting easily. But counting requires additional space. Here we can use xor (^) operation based on some interesting observations:  A^A = 0, here A is any number A^0 = A, here A is any number Since all the number appears twice except one, then all the number appear even numbers will be cancelled out, and only the number appears one time is left, which is what we want. See the code below: class Solution { public: int singleNumber(vector<int>& nums) { int res = 0; for(auto ...

Algorithm Advance Outline

Who wants to read these notes? 1. the one who wants to learn algorithm; 2. the one who has a planned interview in a short amount of time, such as one month later; 3. purely out of curiosity; 4. all the rest. The primary purpose for these posts is to help anyone who wants to learn algorithm in a short amount of time and be ready for coding interviews with tech companies, such as, Amazon, Facebook, Microsoft, etc. Before you start, you are expected to already know:  1. the fundamentals of at least one programming language; 2. the fundamentals of data structures. If you do not have these basics, it is better to "google and read" some intro docs, which should NOT take large amount of time. Of course, you can always learn whenever see a "unknown" data structure or line in the codes. Remember, "google and read" is always one of keys to learning. Common algorithms: 1. Recursion 2. Binary search 3. Dynamic programming 4. Breadth-first search 5. Depth-first search...