<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>

class Solution:
    def colorTheGrid(self, m: int, n: int) -> int:
        MOD = 1000000007
        valid_rows = self.generate_valid_rows(m)
        adj_matrix = self.build_adjacency_matrix(valid_rows)
        dp = [1] * len(valid_rows)
        
        for _ in range(n - 1):
            dp_next = [0] * len(valid_rows)
            for i, row in enumerate(valid_rows):
                for j, adj_row in enumerate(valid_rows):
                    if adj_matrix[i][j]:
                        dp_next[j] += dp[i]
                        dp_next[j] %= MOD
            dp = dp_next
        
        return sum(dp) % MOD

    def generate_valid_rows(self, m: int) -> list:
        valid_rows = []
        for i in range(3 ** m):
            row = []
            for j in range(m):
                row.append((i // (3 ** j)) % 3)
            if all(row[k] != row[k + 1] for k in range(m - 1)):
                valid_rows.append(tuple(row))
        return valid_rows

    def build_adjacency_matrix(self, valid_rows: list) -> list:
        adj_matrix = [[False] * len(valid_rows) for _ in range(len(valid_rows))]
        for i, row1 in enumerate(valid_rows):
            for j, row2 in enumerate(valid_rows):
                if all(row1[k] != row2[k] for k in range(len(row1))):
                    adj_matrix[i][j] = True
        return adj_matrix
659