Given three integers N, M and K. The task is to find the number of ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors.
Input: N = 3, M = 2, K = 1
Let the colors be 1 and 2, so the ways are:
1, 1, 2
1, 2, 2
2, 2, 1
2, 1, 1
Above 4 ways have exactly one pair of adjacent elements with different color.
Input: N = 3, M = 3, K = 2
Approach: We can use Dynamic Programming with memoisation to solve the above problem. There are N positions to fill, hence the recursive function will compose of two calls, one if the next position is filled with the same color and the other if it is filled with a different color. Hence the recursive calls will be:
- countWays(index + 1, cnt), if the next index is filled with same color.
- (m – 1) * countWays(index + 1, cnt + 1), if the next index is filled with a different color. The number of ways get multiplied with (m – 1).
The bases cases will be:
- If index = n, then a check for the value of cnt is done. If cnt = K then it is a possible way hence return 1, else return 0.
- To avoid repetitive calls, memoize the returned value in a 2-D array and return this value if the recursive call with same parameters is done again.
Below is the implementation of the above approach:
- Minimum colors required such that edges forming cycle do not have same color
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Count number of ways to fill a "n x 4" grid using "1 x 4" tiles
- Color N boxes using M colors such that K boxes have different color from the box on its left
- Number of ways to form an array with distinct adjacent elements
- Minimize the count of adjacent pairs with different parity
- Count possible combinations of pairs with adjacent elements from first N numbers
- Flood fill Algorithm - how to implement fill() in paint?
- Ways to arrange Balls such that adjacent balls are of different types
- Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
- Number of pairs such that path between pairs has the two vertices A and B
- Flood Fill Algorithm
- Minimum cost to fill given weight in a bag
- Balanced expressions such that given positions have opening brackets
- Balanced expressions such that given positions have opening brackets | Set 2
- Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range
- Count of Numbers in a Range divisible by m and having digit d in even positions
- Java Applet | Implementing Flood Fill algorithm
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Maximum sum such that no two elements are adjacent | Set 2