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
Painting a Grid With Three Different Colors INPUT 1 x 1 Grid Available Colors: Red Green Blue m = 1 (rows) n = 1 (columns) MOD = 10^9 + 7 ALGORITHM (DP) 1 Define States Each column pattern as a unique state 2 Base Case For m=1, n=1: single cell can be R, G, or B 3 Count Valid Patterns No adjacent constraint for 1x1 grid 4 Apply Modulo Result % (10^9 + 7) 3 % MOD = 3 DP Transition dp[col][pattern] = sum of valid prev patterns For 1x1: dp[0] = 3 FINAL RESULT All Valid Colorings: Red Green Blue Total: 1 + 1 + 1 = 3 OUTPUT 3 OK - Verified 3 ways to paint a 1x1 grid Key Insight: For larger grids, use DP where each state represents a valid column coloring pattern. Transition: count compatible patterns between adjacent columns (no same color horizontally). Time: O(n * 3^m * 3^m) | For m=1, n=1: simply count available colors = 3 TutorialsPoint - Painting a Grid With Three Different Colors | Dynamic Programming Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen