Number of ways to color boundary of each block of M*N table
Last Updated :
12 Nov, 2021
Given a table of M * N. There are total M * N squares of size 1. You have to colour each side of all squares with 3 colour Orange, Blue or Black such that each square have 2 different colours and each colour must occur twice.
It means each square have four sides, 2 of them is orange and 2 of them is Blue or 2 of them is orange and 2 of them is Black or 2 of them is Blue and 2 of them is Black.
Examples:
Input: N = 1, M = 1
Output: 18
Explanation:
We can fill the upper part of the square and left part of the square with any of the three colours. So the number of ways is 3*3,
Now for filling the right and the lower part, we have only 2 option if upper and left have the same colour.
If the upper and the left part have different colour then we can use those two colours to fill the right and lower part, it has also 2 option. The number of combination to fill right and lower is 2.
A total possible way to colour the square is 3*3*2 = 18
Input: N = 3, M = 2
Output: 15552
Approach:
- Find the number of ways to fill the upper and right side of the rectangle. Upper-side has M units and the right side has N units. So, The number of ways to colour the upper and the right side of the rectangle is pow(3, M + N) because each has 3 option.
- Now, For filling the lower and the left side of each square, It has 2 option for each square then the number of ways is pow(2, M * N).
- Final result is:
Total count = pow(3, M + N ) * pow(2, M * N)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int CountWays( int N, int M)
{
int count = 1;
count = pow (3, M + N);
count *= pow (2, M * N);
return count;
}
int main()
{
int N = 3;
int M = 2;
cout << CountWays(N, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int CountWays( int N, int M)
{
int count = 1 ;
count = ( int )Math.pow( 3 , M + N);
count *= ( int )Math.pow( 2 , M * N);
return count;
}
public static void main(String args[])
{
int N = 3 ;
int M = 2 ;
System.out.println(CountWays(N, M));
}
}
|
Python3
def CountWays(N, M):
count = 1
count = pow ( 3 , M + N)
count * = pow ( 2 , M * N);
return count
N = 3
M = 2
print (CountWays(N, M))
|
C#
using System;
class GFG{
static int CountWays( int N, int M)
{
int count = 1;
count = ( int )Math.Pow(3, M + N);
count *= ( int )Math.Pow(2, M * N);
return count;
}
static void Main()
{
int N = 3;
int M = 2;
Console.Write(CountWays(N, M));
}
}
|
Javascript
<script>
function CountWays(N, M)
{
var count = 1;
count = Math.pow(3, M + N);
count *= Math.pow(2, M * N);
return count;
}
var N = 3;
var M = 2;
document.write( CountWays(N, M));
</script>
|
Time Complexity: O(log (m * n))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...