Similar Problems

Similar Problems not available

Count Distinct Numbers On Board - Leetcode Solution

Companies:

LeetCode:  Count Distinct Numbers On Board Leetcode Solution

Difficulty: Easy

Topics: math hash-table array simulation  

Problem Description:

You have a board of size n x m representing a group of N * M cells, each cell is marked with an integer representing the color of that cell.

You are given an integer k, which is the maximum number of adjacent equal colors you can choose from the board.

Return the number of ways you can paint the board using the following rules:

  • You can paint only adjacent cells.
  • You are allowed to change the color of any cell.
  • Once you paint a cell, its adjacent cells with the same color must be painted with the same color.

Solution Approach:

The problem can be solved using dynamic programming. We will maintain a 2D array dp[i][j][k], where i and j represents the current row and column respectively, and k represents the number of adjacent cells we can paint with same color.

The base case would be when we reach the end of the board, i.e. i = n. In this case, there is only one way to paint the board.

For each cell dp[i][j][k], we can have four options:

  • Paint the current cell with a new color.
  • Paint the current cell with an existing color from any of its adjacent cells, but only if k is greater than or equal to the number of adjacent cells with the same color.
  • Leave the current cell as it is and move to the next cell.
  • If the current cell is the last cell in a row, then we can also consider skipping to the next row.

The recurrence relation to calculate the number of ways for each cell would be:

dp[i][j][k] = dp[i][j+1][k-1] (If we paint the current cell with an existing color from its right adjacent cell) dp[i][j][k] += dp[i][j-1][k-1] (If we paint the current cell with an existing color from its left adjacent cell) dp[i][j][k] += dp[i+1][j][k] (If we skip to the next row) dp[i][j][k] += dp[i][j+1][k-1] + dp[i][j-1][k-1] (If we paint the current cell with a new color)

We will start calculating the answers from bottom up, i.e. row n and move upwards.

The final answer would be the sum of all dp[0][0][k] (0 <= k <= K).

Code:

int mod = 1e9+7;

int countPatterns(int n, int m, int K) { vector<vector<vector<int>>> dp(n, vector<vector<int>>(m,vector<int>(K+1,0))); for(int i=0;i<m;i++) dp[n-1][i][0] = 1;

for(int i=n-2;i>=0;i--){
    for(int j=m-1;j>=0;j--){
        for(int k=0;k<=K;k++){
            dp[i][j][k] = ((j+1<m ? dp[i][j+1][k-1]: 0) + (j>0 ? dp[i][j-1][k-1] : 0) + dp[i+1][j][k])%mod;
            if(k>0) dp[i][j][k] = (dp[i][j][k] + ((j+1<m? dp[i][j+1][k-1] : 0) + (j>0 ? dp[i][j-1][k-1] : 0))%mod)%mod;
        }
    }
}

int ans = 0;
for(int k=0;k<=K;k++) ans = (ans+dp[0][0][k])%mod;
return ans;

}

Count Distinct Numbers On Board Solution Code

1