Color N boxes using M colors such that K boxes have different color from the box on its left
Given N number of boxes arranged in a row and M number of colors. The task is to find the number of ways to paint those N boxes using M colors such that there are exactly K boxes with a color different from the color of the box on its left. Print this answer modulo 998244353.
Examples:Â
Â
Input: N = 3, M = 3, K = 0Â
Output: 3Â
Since the value of K is zero, no box can have a different color from color of the box on its left. Thus, all boxes should be painted with same color and since there are 3 types of colors, so there are total 3 ways.Â
Input: N = 3, M = 2, K = 1Â
Output: 4Â
Let’s number the colors as 1 and 2. Four possible sequences of painting 3 boxes with 1 box having different color from color of box on its left are (1 2 2), (1 1 2), (2 1 1) (2 2 1)Â
Â
Prerequisites : Dynamic Programming
Â
Approach: This problem can be solved using dynamic programming where dp[i][j] will denote the number of ways to paint i boxes using M colors such that there are exactly j boxes with a color different from the color of the box on its left. For every current box except 1st, either we can paint the same color as painted on its left box and solve for dp[i – 1][j] or we can paint it with remaining M – 1 color and solve for dp[i – 1][j – 1] recursively.
Steps to follow to according to above approach:
- If idx is greater than N, then check if diff is equal to K.
- *If diff is equal to K, then return 1.
     *Else, return 0.
- *If diff is equal to K, then return 1.
- If the result for the current value of idx and diff is not equal to -1 then return the precomputed result dp[idx].
- Otherwise, recursively call solve() function with idx+1, diff, N, M, and K and store the result in the variable ans.
- recursively call solve() function with idx+1, diff+1, N, M, and K, and multiply the result with (M-1).
- add the value obtained in step 5 to the result obtained in step 4, and take its modulo with MOD.
- store the result obtained in step 6 in the dp array for the current value of idx and diff, and return the same value.
Below is the code to implement the above approach:Â
Â
C++
// CPP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left #include <bits/stdc++.h> using namespace std; Â
const int MOD = 998244353; Â
vector<vector< int >> dp; Â
// This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left int solve( int idx, int diff, int N, int M, int K) {     // Base Case     if (idx > N) {         if (diff == K)             return 1;         return 0;     } Â
    // If already computed     if (dp[idx][ diff] != -1)         return dp[idx][ diff]; Â
    // Either paint with same color as     // previous one     int ans = solve(idx + 1, diff, N, M, K); Â
    // Or paint with remaining (M - 1)     // colors     ans = ans % MOD + ((M - 1) % MOD * solve(idx + 1, diff + 1, N, M, K) % MOD) % MOD; Â
    return dp[idx][ diff] = ans; } Â
// Driver code int main() { Â Â Â Â int N = 3, M = 3, K = 0; Â Â Â Â dp = vector<vector< int >>(N+1,vector< int >(N+1,-1)); Â
    // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     cout << (M * solve(2, 0, N, M, K)) << endl; Â
    return 0; } |
Java
// Java Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left Â
class GFG { Â Â Â Â Â Â Â Â Â static int M = 1001 ; Â Â Â Â static int MOD = 998244353 ; Â
    static int [][] dp = new int [M][M]; Â
    // This function returns the required number     // of ways where idx is the current index and     // diff is number of boxes having different     // color from box on its left     static int solve( int idx, int diff,                         int N, int M, int K)     {         // Base Case         if (idx > N)         {             if (diff == K)                 return 1 ;             return 0 ;         } Â
        // If already computed         if (dp[idx][ diff] != - 1 )             return dp[idx][ diff]; Â
        // Either paint with same color as         // previous one         int ans = solve(idx + 1 , diff, N, M, K); Â
        // Or paint with remaining (M - 1)         // colors         ans += (M - 1 ) * solve(idx + 1 ,                 diff + 1 , N, M, K); Â
        return dp[idx][ diff] = ans % MOD;     } Â
    // Driver code     public static void main (String[] args)     {         int N = 3 , M = 3 , K = 0 ;         for ( int i = 0 ; i <= M; i++)             for ( int j = 0 ; j <= M; j++)                 dp[i][j] = - 1 ;              // Multiply M since first box can be         // painted with any of the M colors and         // start solving from 2nd box         System.out.println((M * solve( 2 , 0 , N, M, K)));     } } Â
// This code is contributed by mits |
Python3
# Python3 Program to Paint N boxes using M # colors such that K boxes have color # different from color of box on its left Â
M = 1001 ; MOD = 998244353 ; Â
dp = [[ - 1 ] * M ] * M Â
# This function returns the required number # of ways where idx is the current index and # diff is number of boxes having different # color from box on its left def solve(idx, diff, N, M, K) :          # Base Case     if (idx > N) :         if (diff = = K) :             return 1         return 0 Â
    # If already computed     if (dp[idx][ diff] ! = - 1 ) :         return dp[idx]; Â
    # Either paint with same color as     # previous one     ans = solve(idx + 1 , diff, N, M, K); Â
    # Or paint with remaining (M - 1)     # colors     ans + = (M - 1 ) * solve(idx + 1 , diff + 1 , N, M, K); Â
    dp[idx][ diff] = ans % MOD;          return dp[idx][ diff] Â
# Driver code if __name__ = = "__main__" : Â
    N = 3     M = 3     K = 0 Â
    # Multiply M since first box can be     # painted with any of the M colors and     # start solving from 2nd box     print (M * solve( 2 , 0 , N, M, K)) Â
# This code is contributed by Ryuga |
C#
// C# Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left using System; class GFG { Â Â Â Â Â static int M = 1001; static int MOD = 998244353; Â
static int [,] dp = new int [M, M]; Â
// This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve( int idx, int diff,                  int N, int M, int K) {     // Base Case     if (idx > N)     {         if (diff == K)             return 1;         return 0;     } Â
    // If already computed     if (dp[idx, diff] != -1)         return dp[idx, diff]; Â
    // Either paint with same color as     // previous one     int ans = solve(idx + 1, diff, N, M, K); Â
    // Or paint with remaining (M - 1)     // colors     ans += (M - 1) * solve(idx + 1,                 diff + 1, N, M, K); Â
    return dp[idx, diff] = ans % MOD; } Â
// Driver code public static void Main () { Â Â Â Â int N = 3, M = 3, K = 0; Â Â Â Â for ( int i = 0; i <= M; i++) Â Â Â Â Â Â Â Â for ( int j = 0; j <= M; j++) Â Â Â Â Â Â Â Â Â Â Â Â dp[i, j] = -1; Â
    // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     Console.WriteLine((M * solve(2, 0, N, M, K))); } } Â
// This code is contributed by chandan_jnu |
Javascript
<script> Â
    // JavaScript Program to Paint N boxes using M     // colors such that K boxes have color     // different from color of box on its left          let m = 1001;     let MOD = 998244353;        let dp = new Array(m);     for (let i = 0; i < m; i++)     {         dp[i] = new Array(m);         for (let j = 0; j < m; j++)         {             dp[i][j] = 0;         }     }        // This function returns the required number     // of ways where idx is the current index and     // diff is number of boxes having different     // color from box on its left     function solve(idx, diff, N, M, K)     {         // Base Case         if (idx > N)         {             if (diff == K)                 return 1;             return 0;         }            // If already computed         if (dp[idx][ diff] != -1)             return dp[idx][ diff];            // Either paint with same color as         // previous one         let ans = solve(idx + 1, diff, N, M, K);            // Or paint with remaining (M - 1)         // colors         ans += (M - 1) * solve(idx + 1,                 diff + 1, N, M, K);           dp[idx][ diff] = ans % MOD;         return dp[idx][ diff];     }          let N = 3, M = 3, K = 0;     for (let i = 0; i <= M; i++)       for (let j = 0; j <= M; j++)         dp[i][j] = -1; Â
    // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     document.write((M * solve(2, 0, N, M, K)));      </script> |
PHP
<?php // PHP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left Â
$M = 1001; $MOD = 998244353; Â
$dp = array_fill (0, $M , Â Â Â Â Â Â array_fill (0, $M , -1)); Â
// This function returns the required number // of ways where idx is the current index // and diff is number of boxes having // different color from box on its left function solve( $idx , $diff , $N , $M , $K ) {     global $dp , $MOD ;          // Base Case     if ( $idx > $N )     {         if ( $diff == $K )             return 1;         return 0;     } Â
    // If already computed     if ( $dp [ $idx ][ $diff ] != -1)         return $dp [ $idx ][ $diff ]; Â
    // Either paint with same color     // as previous one     $ans = solve( $idx + 1, $diff , $N , $M , $K ); Â
    // Or paint with remaining (M - 1)     // colors     $ans += ( $M - 1) * solve( $idx + 1,              $diff + 1, $N , $M , $K ); Â
    return $dp [ $idx ][ $diff ] = $ans % $MOD ; } Â
// Driver code $N = 3; $M = 3; $K = 0; Â
// Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box echo ( $M * solve(2, 0, $N , $M , $K )); Â
// This code is contributed by chandan_jnu ?> |
3
Time Complexity: O(M*M)
Auxiliary Space: O(M*M)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a DP to store the solution of the subproblems .
- Initialize the DP with base cases by initializing the first row of DP.
- Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
- Return the final solution stored in dp[1][K].
Implementation :
C++
// CPP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left Â
#include <bits/stdc++.h> using namespace std; Â
const int MOD = 998244353; Â
int dp[2][1010]; Â
// This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left int solve( int N, int M, int K) {     // Initialize the first row of dp table     for ( int i = 0; i <= N; i++) {         dp[0][i] = 1;     } Â
    // Process the remaining rows     for ( int i = 2; i <= N + 1; i++) {         for ( int j = 0; j <= N; j++) {             int ans = dp[0][j]; Â
            if (j == 0) {                 ans = (M * dp[1][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD;             } Â
            dp[0][j] = ans;         } Â
        // Swap the arrays         swap(dp[0], dp[1]);     }          // return final answer     return dp[1][K]; } Â
// Driver code int main() {     int N = 3, M = 3, K = 0;          // function call     cout << (M * solve(N, M, K + 1)) % MOD << endl; Â
    return 0; } |
Java
// Java Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left Â
import java.util.*; Â
public class Main { Â Â static final int MOD = 998244353 ; Â
static int [][] dp; Â
// This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve( int N, int M, int K) {     // Initialize the first row of dp table     for ( int i = 0 ; i <= N; i++) {         dp[ 0 ][i] = 1 ;     } Â
    // Process the remaining rows     for ( int i = 2 ; i <= N + 1 ; i++) {         for ( int j = 0 ; j <= N; j++) {             int ans = dp[ 0 ][j]; Â
            if (j == 0 ) {                 ans = (M * dp[ 1 ][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1 ) % MOD * dp[ 1 ][j - 1 ]) % MOD) % MOD;             } Â
            dp[ 0 ][j] = ans;         } Â
        // Swap the arrays         int [] temp = dp[ 0 ];         dp[ 0 ] = dp[ 1 ];         dp[ 1 ] = temp;     } Â
    // return final answer     return dp[ 1 ][K]; } Â
// Driver code public static void main(String[] args) { Â Â Â Â int N = 3 , M = 3 , K = 0 ; Â
    // Initialize dp array     dp = new int [ 2 ][ 1010 ]; Â
    // function call     System.out.println((M * solve(N, M, K + 1 )) % MOD); } } |
Python3
MOD = 998244353 Â
# This function returns the required number # of ways where idx is the current index and # diff is number of boxes having different # color from box on its left def solve(N, M, K):     global dp          # Initialize the first row of dp table     for i in range (N + 1 ):         dp[ 0 ][i] = 1 Â
    # Process the remaining rows     for i in range ( 2 , N + 2 ):         for j in range (N + 1 ):             ans = dp[ 0 ][j] Â
            if j = = 0 :                 ans = (M * dp[ 1 ][j]) % MOD             else :                 ans = (ans % MOD + ((M - 1 ) % MOD * dp[ 1 ][j - 1 ]) % MOD) % MOD Â
            dp[ 0 ][j] = ans Â
        # Swap the arrays         dp[ 0 ], dp[ 1 ] = dp[ 1 ], dp[ 0 ] Â
    # return final answer     return dp[ 1 ][K] Â
# Driver code if __name__ = = '__main__' : Â Â Â Â N, M, K = 3 , 3 , 0 Â
    # Initialize dp array     dp = [[ 0 ] * 1010 for _ in range ( 2 )] Â
    # function call     print ((M * solve(N, M, K + 1 )) % MOD) |
Javascript
// JavaScript Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left Â
const MOD = 998244353; Â
// This function returns the required number // of ways where idx is the current index and // diff is the number of boxes having a different // color from the box on its left function solve(N, M, K) {     // Initialize a 2D array for dynamic programming     const dp = new Array(2).fill().map(() => new Array(N + 1).fill(0)); Â
    // Initialize the first row of dp table     for (let i = 0; i <= N; i++) {         dp[0][i] = 1;     } Â
    // Process the remaining rows     for (let i = 2; i <= N + 1; i++) {         for (let j = 0; j <= N; j++) {             let ans = dp[0][j]; Â
            if (j === 0) {                 ans = (M * dp[1][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD;             } Â
            dp[0][j] = ans;         } Â
        // Swap the arrays         [dp[0], dp[1]] = [dp[1], dp[0]];     } Â
    // Return the final answer     return dp[1][K]; } Â
// Driver code const N = 3, M = 3, K = 0; Â
// Function call console.log((M * solve(N, M, K + 1)) % MOD); Â
// This code is contributed by prasad264 |
Output:Â
3
Â
Time Complexity: Â O(N * N)
Auxiliary Space: Â O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!