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:
- 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
- Flood fill Algorithm - how to implement fill() in paint?
- Ways to arrange Balls such that adjacent balls are of different types
- 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
- Java Applet | Implementing Flood Fill algorithm
- Count of Numbers in a Range divisible by m and having digit d in even positions
- 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
- Maximum sum such that no two elements are adjacent | Set 2
- Count of subsets not containing adjacent elements
- Maximum sum in a 2 x n grid such that no two elements are adjacent
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.