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

Brute Force - Question 2

2105. Watering Plants II Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously. It takes the same amount of time to water each plant regardless of how much water it needs. Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant. In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice ...

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...

Dynamic Programming - Easy Level - Question 1

Dynamic Programming - Easy Level - Question 1 Leetcode 1646  Get Maximum in Generated Array You are given an integer n. An array nums of length n + 1 is generated in the following way: nums[0] = 0 nums[1] = 1 nums[2 * i] = nums[i] when 2 <= 2 * i <= n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n Return the maximum integer in the array nums​​​. Constraints: 0 <= n <= 100 Analysis: This question is quick straightforward: the state and transitional formula are given; the initialization is also given. So we can just ready the code to iterate all the states and find the maximum. See the code below: class Solution { public: int getMaximumGenerated(int n) { int res = 0; if(n<2) return n; vector<int> f(n+1, 0); f[1] = 1; for(int i=2; i<=n; ++i) { if(i&1) f[i] = f[i/2] + f[i/2+1]; else f[i] = f[i/2]; // cout<<i<<" "<<f[i]<<endl; ...