The Wayback Machine - https://web.archive.org/web/20240804233400/https://www.geeksforgeeks.org/painting-fence-algorithm/
Open In App

Painting Fence Algorithm

Last Updated : 01 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since the answer can be large, return it modulo 10^9 + 7.

Examples:

Input : n = 2 k = 4
Output : 16
Explanation: We have 4 colors and 2 posts.
Ways when both posts have same color : 4 
Ways when both posts have diff color :4(choices for 1st post) * 3(choices for 2nd post) = 12

Input : n = 3 k = 2
Output : 6

The following image depicts the 6 possible ways of painting 3 posts with 2 colors:



Consider the following image, in which c, c’ and c” are the respective colors of posts i, i-1, and i -2.



According to the constraint of the problem, c = c’ = c” is not possible simultaneously, so either c’ != c or c” != c or both. There are k – 1 possibility for c’ != c and k – 1 for c” != c.

 diff = number of ways when color of last
two posts is different
same = number of ways when color of last
two posts is same
Total ways = diff + same

for n = 1
diff = k, same = 0
total = k

for n = 2
diff = k * (k-1) //k choices for
first post, k-1 for next
same = k/k choices for common
color of two posts
total = k + k * (k-1)

for n = 3
diff = (previous total ways) * (k - 1)
(k + k * (k - 1) * (k - 1)
same = previous diff ways
k * (k-1)


Hence, we deduce that,
total[i] = same[i] + diff[i]
same[i] = diff[i-1]
diff[i] = total[i-1] * (k-1)

Below is the implementation of the problem:

C++
// C++ program for Painting Fence Algorithm
// optimised version

#include <bits/stdc++.h>
using namespace std;

// Returns count of ways to color k posts
long countWays(int n, int k)
{
    long dp[n + 1];
    memset(dp, 0, sizeof(dp));
    long long mod = 1000000007;

    dp[1] = k;
    dp[2] = k * k;

    for (int i = 3; i <= n; i++) {
        dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod;
    }

    return dp[n];
}

// Driver code
int main()
{
    int n = 3, k = 2;
    cout << countWays(n, k) << endl;
    return 0;
}
Java
// Java program for Painting Fence Algorithm
import java.util.*;

class GfG {

    // Returns count of ways to color k posts
    // using k colors
    static long countWays(int n, int k)
    {
        // To store results for subproblems
        long dp[] = new long[n + 1];
        Arrays.fill(dp, 0);
        int mod = 1000000007;

        // There are k ways to color first post
        dp[1] = k;

        // There are 0 ways for single post to
        // violate (same color_ and k ways to
        // not violate (different color)
        int same = 0, diff = k;

        // Fill for 2 posts onwards
        for (int i = 2; i <= n; i++) {
            // Current same is same as previous diff
            same = diff;

            // We always have k-1 choices for next post
            diff = (int)(dp[i - 1] * (k - 1));
            diff = diff % mod;

            // Total choices till i.
            dp[i] = (same + diff) % mod;
        }

        return dp[n];
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 3, k = 2;
        System.out.println(countWays(n, k));
    }
}

// This code contributed by Rajput-Ji
Python
# Python3 program for Painting Fence Algorithm 
# optimised version

# Returns count of ways to color k posts 
def countWays(n, k):
    
    dp = [0] * (n + 1)
    total = k 
    mod = 1000000007
    
    dp[1] = k
    dp[2] = k * k    
    
    for i in range(3,n+1):
        dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod
        
    return dp[n]
  
# Driver code 
n = 3
k = 2
print(countWays(n, k))
 
# This code is contributed by shubhamsingh10
C#
// C# program for Painting Fence Algorithm
using System;
public class GFG
{

  // Returns count of ways to color k posts
  // using k colors
  static long countWays(int n, int k)
  {

    // To store results for subproblems
    long[] dp = new long[n + 1];
    Array.Fill(dp, 0);
    int mod = 1000000007;

    // There are k ways to color first post
    dp[1] = k;

    // There are 0 ways for single post to
    // violate (same color_ and k ways to
    // not violate (different color)
    int same = 0, diff = k;

    // Fill for 2 posts onwards
    for (int i = 2; i <= n; i++) 
    {

      // Current same is same as previous diff
      same = diff;

      // We always have k-1 choices for next post
      diff = (int)(dp[i - 1] * (k - 1));
      diff = diff % mod;

      // Total choices till i.
      dp[i] = (same + diff) % mod;
    }

    return dp[n];
  }

  // Driver code
  static public void Main ()
  {
    int n = 3, k = 2;
    Console.WriteLine(countWays(n, k));
  }
}

// This code is contributed by avanitrachhadiya2155
JavaScript
<script>
    // Javascript program for Painting Fence Algorithm
    
    // Returns count of ways to color k posts
    // using k colors
    function countWays(n, k)
    {

      // To store results for subproblems
      let dp = new Array(n + 1);
      dp.fill(0);
      let mod = 1000000007;

      // There are k ways to color first post
      dp[1] = k;

      // There are 0 ways for single post to
      // violate (same color_ and k ways to
      // not violate (different color)
      let same = 0, diff = k;

      // Fill for 2 posts onwards
      for (let i = 2; i <= n; i++)
      {

        // Current same is same as previous diff
        same = diff;

        // We always have k-1 choices for next post
        diff = (dp[i - 1] * (k - 1));
        diff = diff % mod;

        // Total choices till i.
        dp[i] = (same + diff) % mod;
      }

      return dp[n];
    }
    
    let n = 3, k = 2;
    document.write(countWays(n, k));
    
    // This code is contributed by divyeshrabadiya07.
</script>

Output
6

Time Complexity: O(N)
Auxiliary Space: O (N)

Space optimization : 
We can optimize the above solution by use one variable instead of a table.
Below is the implementation of the problem:

C++
// C++ program for Painting Fence Algorithm
#include <bits/stdc++.h>
using namespace std;

// Returns count of ways to color k posts
// using k colors
long countWays(int n, int k)
{
    // There are k ways to color first post
    long total = k;
    int mod = 1000000007;

    // There are 0 ways for single post to
    // violate (same color) and k ways to
    // not violate (different color)
    int same = 0, diff = k;

    // Fill for 2 posts onwards
    for (int i = 2; i <= n; i++) {
        // Current same is same as previous diff
        same = diff;

        // We always have k-1 choices for next post
        diff = (total * (k - 1)) % 1000000007;
        

        // Total choices till i.
        total = (same + diff) % mod;
    }

    return total;
}

// Driver code
int main()
{
    int n = 3, k = 2;
    cout << countWays(n, k) << endl;
    return 0;
}
Java
// Java program for Painting Fence Algorithm
class GFG {

    // Returns count of ways to color k posts
    // using k colors
    static long countWays(int n, int k)
    {
        // There are k ways to color first post
        long total = k;
        int mod = 1000000007;

        // There are 0 ways for single post to
        // violate (same color_ and k ways to
        // not violate (different color)
        int same = 0, diff = k;

        // Fill for 2 posts onwards
        for (int i = 2; i <= n; i++) {
            // Current same is same as previous diff
            same = diff;

            // We always have k-1 choices for next post
            diff = ((int)total * (k - 1) )% 1000000007;
        

            // Total choices till i.
            total = (same + diff) % mod;
        }
        return total;
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 3, k = 2;
        System.out.println(countWays(n, k));
    }
}

// This code is contributed by Mukul Singh
Python
# Python3 program for Painting 
# Fence Algorithm 

# Returns count of ways to color k posts using k colors 
def countWays(n, k) :

    # There are k ways to color first post 
    total = k
    mod = 1000000007

    # There are 0 ways for single post to 
    # violate (same color_ and k ways to 
    # not violate (different color) 
    same, diff = 0, k

    # Fill for 2 posts onwards 
    for i in range(2, n + 1):
        
        # Current same is same as previous diff 
        same = diff 

        # We always have k-1 choices for next post 
        diff = (total * ((k - 1) % 1000000007)) % 1000000007

        # Total choices till i. 
        total = (same + diff) % mod 
    
    return total

# Driver code 
if __name__ == "__main__" :

    n, k = 3, 2
    print(countWays(n, k)) 

# This code is contributed by @nibeditans
C#
// C# program for Painting Fence Algorithm
using System;

class GFG {
    // Returns count of ways to color k posts
    // using k colors
    static long countWays(int n, int k)
    {
        // There are k ways to color first post
        long total = k;
        int mod = 1000000007;

        // There are 0 ways for single post to
        // violate (same color_ and k ways to
        // not violate (different color)
        long same = 0, diff = k;

        // Fill for 2 posts onwards
        for (int i = 2; i <= n; i++) {
            // Current same is same as previous diff
            same = diff;

            // We always have k-1 choices for next post
            diff = (total * (k - 1))%1000000007;

            // Total choices till i.
            total = (same + diff) % mod;
        }

        return total;
    }

    // Driver code
    static void Main()
    {
        int n = 3, k = 2;
        Console.Write(countWays(n, k));
    }
}

// This code is contributed by DrRoot_
JavaScript
<script>

    // JavaScript program for Painting Fence Algorithm
    
    // Returns count of ways to color k posts
    // using k colors
    function countWays(n, k)
    {
        // There are k ways to color first post
        let total = k;
        let mod = 1000000007;
 
        // There are 0 ways for single post to
        // violate (same color_ and k ways to
        // not violate (different color)
        let same = 0, diff = k;
 
        // Fill for 2 posts onwards
        for (let i = 2; i <= n; i++) {
            // Current same is same as previous diff
            same = diff;
 
            // We always have k-1 choices for next post
            diff = (total * (k - 1))%1000000007;
 
            // Total choices till i.
            total = (same + diff) % mod;
        }
 
        return total;
    }
    
    let n = 3, k = 2;
      document.write(countWays(n, k));
        
</script>
PHP
<?php 
// PHP program for Painting Fence Algorithm

// Returns count of ways to color k 
// posts using k colors
function countWays($n, $k)
{
    // There are k ways to color first post
    $total = $k;
    $mod = 1000000007;

    // There are 0 ways for single post to
    // violate (same color_ and k ways to
    // not violate (different color)
    $same = 0;
    $diff = $k;

    // Fill for 2 posts onwards
    for ($i = 2; $i <= $n; $i++)
    {
        // Current same is same as previous diff
        $same = $diff;

        // We always have k-1 choices for next post
        $diff = ($total * ($k - 1)) % $mod;

        // Total choices till i.
        $total = ($same + $diff) % $mod;
    }

    return $total;
}

// Driver code
$n = 3;
$k = 2;
echo countWays($n, $k) . "\n";

// This code is contributed by ita_c
?>

Output
6

Time Complexity: O(N)
Auxiliary Space: O(1)

 




Previous Article
Next Article

Similar Reads

Painting Fence Algorithm in Python
Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since the answer can be large, return it modulo 10^9 + 7. Input : n = 2 k = 4Output : 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color : 4 Ways when both posts have diff c
3 min read
Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
Problem: Given 2 process i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. We strongly recommend to refer below basic solution discussed in previous article. Peterson's Algorithm for Mutual Exclusion | Set 1We would be resolving 2 issues in the previous algorithm.  Wast
11 min read
Rail Fence Cipher - Encryption and Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm. The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded. Examples:  EncryptionInput : "GeeksforGeeks "Key = 3Output : GsGsekfrek eoeDecryptionInput : GsGsekf
15 min read
Cost of painting n * m grid
Given two integers n and m which are the dimensions of a grid. The task is to find the cost of painting the grid cell by cell where the cost of painting a cell is equal to the number of painted cells adjacent to it. Any cell can be painted at any time if it hasn't been painted already, minimize the cost of painting the grid. Examples: Input: n = 1,
4 min read
Minimize cost of painting N houses such that adjacent houses have different colors
Given an integer N and a 2D array cost[][3], where cost[i][0], cost[i][1], and cost[i][2] is the cost of painting ith house with colors red, blue, and green respectively, the task is to find the minimum cost to paint all the houses such that no two adjacent houses have the same color. Examples: Input: N = 3, cost[][3] = {{14, 2, 11}, {11, 14, 5}, {
14 min read
Maximum houses that can be painted continuously when the painting duration and date limit is given
Given an array arr[][] consisting of N pairs such that each pair {L, R} represents that ith house can be painted in L number of days before the Rth day, the task is to find the maximum number of house that can be painted continuously. Examples: Input: N = 4, paint[ ][ ] = [[1, 19], [2, 2], [4, 17], [1, 1]]Output: 3Explanation: Maximum of three hous
7 min read
Minimum Move Required To Fit The Painting in Frame.
Consider a Painting and a Frame having length and breadth as L1, B1 and L2, B2 respectively. Then your task is to output minimum number of moves required to fit that painting into frame by using below operation considering that you are allowed to rotate painting 90° as many times as you want. In each move, you are allowed to cut length or breadth o
7 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all &lt; algorithm &gt; library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
three90RightbarBannerImg