Number of Ways to Paint N × 3 Grid in C++ program

C++Server Side ProgrammingProgramming

<p style="">Suppose we have a grid whose size is n x 3 and we want to paint every cell of the grid with exactly one of the three colors. Here the colors that will be used are Red, Yellow and Green.</p><p>Now there is a constraint, that is no two adjacent cells have the same color. We have n number of rows of the grid. Finally, we have to find the number of ways we can paint this grid. The answer may be very large so return it modulo 10^9 + 7.</p><p>So, if the input is like 1, then the output will be 12</p><p style=""><img src="" class="fr-fic fr-dib" style="width: 418px; height: 160.233px;" width="418" height="160.233"></p><p>To solve this, we will follow these steps &minus;</p><ul class="list"><li><p>m = 10^9 + 7</p></li><li><p>Define a function add(), this will take a, b,</p></li><li><p>return ((a mod m) + (b mod m)) mod m</p></li><li><p>From the main method do the following &minus;</p></li><li><p>a123 := 6, a121 = 6</p></li><li><p>for initialize i := 2, when i &minus;= n, update (increase i by 1), do &minus;</p><ul class="list"><li><p>b121 := add(3 * a121, 2 * a123)</p></li><li><p>b123 := add(2 * a121, 2 * a123)</p></li><li><p>a121 := b121</p></li><li><p>a123 := b123</p></li></ul></li><li><p>return add(a123, a121)</p></li></ul><h2>Example&nbsp;</h2><p>Let us see the following implementation to get better understanding &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long int lli; const lli mod = 1e9 + 7; class Solution { public: &nbsp; &nbsp;lli add(lli a, lli b){ &nbsp; &nbsp; &nbsp; return ((a % mod) + (b % mod)) % mod; &nbsp; &nbsp;} &nbsp; &nbsp;int numOfWays(int n){ &nbsp; &nbsp; &nbsp; lli a123 = 6, a121 = 6; &nbsp; &nbsp; &nbsp; lli b123, b121; &nbsp; &nbsp; &nbsp; for (int i = 2; i &lt;= n; i++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;b121 = add(3 * a121, 2 * a123); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;b123 = add(2 * a121, 2 * a123); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;a121 = b121; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;a123 = b123; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; return add(a123, a121); &nbsp; &nbsp;} }; main(){ &nbsp; &nbsp;Solution ob; &nbsp; &nbsp;cout &lt;&lt; (ob.numOfWays(3)); }</pre><h2>Input</h2><pre class="result notranslate">3</pre><h2>Output</h2><pre class="result notranslate">246</pre>
Updated on 21-Jul-2020 09:15:13