I have 3 valid values: a,b,c I can insert them in a N×3 grid in such a way that no row or column contains cells that are the same values. How can I calculate the number of valid patterns that can be created using N rows?
For example, if N = 4, the total number of valid pattern is 296490.

This is my attempt:
def countPatterns(n):
dp1, dp2 = 6,6
mod = 10 ** 9 + 7
for i in range(2, n+1):
dp1, dp2 = (dp1 * 3 + dp2 * 2) % mod, (dp1 * 2 + dp2 * 2) % mod
return (dp1 + dp2) % mod
When N = 4, the output should be 174 but I'm getting 54.