Painting a Grid With Three Different Colors - Problem
You are given two integers m and n. Consider an m x n grid where each cell is initially white.
You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Two cells are adjacent if they share a side (horizontally or vertically adjacent).
Input & Output
Example 1 — Small Grid
$
Input:
m = 1, n = 1
›
Output:
3
💡 Note:
Single cell can be colored in 3 ways: red, green, or blue
Example 2 — Single Row
$
Input:
m = 1, n = 2
›
Output:
6
💡 Note:
Two adjacent cells must have different colors: RG, RB, GR, GB, BR, BG (6 ways)
Example 3 — Two Rows
$
Input:
m = 1, n = 3
›
Output:
12
💡 Note:
For 3 cells in a row: first cell has 3 choices, each subsequent cell has 2 choices (must be different from previous cell). Total: 3×2×2 = 12 ways.
Constraints
- 1 ≤ m ≤ 5
- 1 ≤ n ≤ 1000
- The answer is guaranteed to be within the range of a 32-bit integer after taking modulo 109 + 7
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code