<p>You are given two integers <code>m</code> and <code>n</code>. Consider an <code>m x n</code> grid where each cell is initially white. You can paint each cell <strong>red</strong>, <strong>green</strong>, or <strong>blue</strong>. All cells <strong>must</strong> be painted.</p>

<p>Return<em> the number of ways to color the grid with <strong>no two adjacent cells having the same color</strong></em>. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/22/colorthegrid.png" style="width: 200px; height: 50px;" />
<pre>
<strong>Input:</strong> m = 1, n = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The three possible colorings are shown in the image above.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/22/copy-of-colorthegrid.png" style="width: 321px; height: 121px;" />
<pre>
<strong>Input:</strong> m = 1, n = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> The six possible colorings are shown in the image above.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> m = 5, n = 5
<strong>Output:</strong> 580986
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= m &lt;= 5</code></li>
	<li><code>1 &lt;= n &lt;= 1000</code></li>
</ul>

MOD = 10**9+7
p = [set() for _ in range(6)]
def getbits(mask,i):
    res =[]
    while mask>0:
        res.append(mask%3)
        mask//=3
    q = i - len(res)
    while q>0:
        res.append(0)
        q-=1
    return res
for i in range(1,6):
    for j in range(3**i):
        u = getbits(j,i)
        flag = True
        for x,y in pairwise(u):
            if x==y: flag=False
        if flag: p[i].add(j)
@cache
def dfs(n,m,mask):
    if n==1: return 1
    res = 0
    g = getbits(mask,m)
    for pre in p[m]:
        u = getbits(pre,m)
        if all(x!=y for x,y in zip(u,g)):
            res+=dfs(n-1,m,pre)
    return res % MOD
ans = [[0]*1001 for _ in range(6)]
for m in range(1,6):
    for n in range(1,1001):
        ans[m][n] = sum(dfs(n,m,mask) for mask in p[m]) % MOD


class Solution:
    def colorTheGrid(self, m: int, n: int) -> int:
        # @cache
        # def dfs(n,mask):
        #     if n==1: return 1
        #     res = 0
        #     g = getbits(mask,m)
        #     for pre in p[m]:
        #         u = getbits(pre,m)
        #         if all(x!=y for x,y in zip(u,g)):
        #             res+=dfs(n-1,pre)
        #     return res % MOD
        # ans = sum(dfs(n,mask) for mask in p[m]) % MOD
        # dfs.cache_clear()
        return ans[m][n]
1903