Practice › Dynamic Programming
Domino Tiling of a 2 × n Board
Easy · Dynamic Programming · Asked at Amazon, Google, TCS, Infosys
Count the ways to completely cover a 2 × n board with 2 × 1 dominoes (each placed upright or lying flat). Print the count modulo 10^9 + 7.
Input
A single integer n.
Output
The number of tilings modulo 10^9 + 7.
Constraints
- 1 ≤ n ≤ 10^6
Look at the left edge: it is covered either by one upright domino (leaving a 2 × (n − 1) board) or by two flat dominoes stacked (leaving 2 × (n − 2)). So ways(n) = ways(n − 1) + ways(n − 2) — the Fibonacci numbers.
Example 1
Input
3
Output
3
Example 2
Input
1
Output
1
Hints
- Look at how the leftmost column is covered.
- Either one upright domino covers it, or two flat dominoes cover it and the next column.
- That gives ways(n) = ways(n − 1) + ways(n − 2).
Approach
ways(0) = 1 (the empty board) and ways(1) = 1. Each larger board starts with either an upright domino (then a 2 × (n − 1) board remains) or two stacked flat dominoes (then 2 × (n − 2) remains), and these cases never overlap. So the counts are Fibonacci numbers; iterate n times keeping two values, taking everything modulo 10^9 + 7.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
const long long MOD = 1000000007LL;
int n;
cin >> n;
long long a = 1, b = 1; // ways(0), ways(1)
for (int i = 2; i <= n; i++) {
long long c = (a + b) % MOD;
a = b;
b = c;
}
cout << b << "\n";
return 0;
}Python solution
MOD = 10**9 + 7
n = int(input())
a, b = 1, 1
for _ in range(2, n + 1):
a, b = b, (a + b) % MOD
print(b)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
final long MOD = 1000000007L;
int n = new Scanner(System.in).nextInt();
long a = 1, b = 1;
for (int i = 2; i <= n; i++) {
long c = (a + b) % MOD;
a = b;
b = c;
}
System.out.println(b);
}
}Solve Domino Tiling of a 2 × n Board online · All practice problems