Problem
Given a number n
, count the number of ways to fill an n x 4
grid using 1 x 4
tiles. Tiles can be placed either horizontally or vertically, and each tile must cover exactly four cells.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Example 4
|
|
Solution
Method - Bottom up DP
Reasoning / Intuition
For each position in the grid, you can either:
- Place a tile horizontally, which reduces the problem to filling an
(n-1) x 4
grid. - Place a tile vertically, which requires 4 consecutive rows, reducing the problem to filling an
(n-4) x 4
grid.
So, suppose we have 5x4 grid, $$ grid = \begin{array}{|c|c|c|c|} \hline & & & \\ \hline & & & \\ \hline & & & \\ \hline & & & \\ \hline & & & \\ \hline \end{array} \text{, tile = } \begin{array}{|c|c|c|c|} \hline \colorbox{green} & \colorbox{green} & \colorbox{green}& \colorbox{green} \\ \hline \end{array} $$
then, when the tile is placed horizontally: $$ grid = \begin{array}{|c|c|c|c|} \hline \colorbox{green} & \colorbox{green} & \colorbox{green} & \colorbox{green} \\ \hline & & & \\ \hline & & & \\ \hline & & & \\ \hline & & & \\ \hline \end{array} $$
and when it is placed vertically: $$ grid = \begin{array}{|c|c|c|c|} \hline \colorbox{green} & & & \\ \hline \colorbox{green} & & & \\ \hline \colorbox{green} & & & \\ \hline \colorbox{green} & & & \\ \hline & & & \\ \hline \end{array} $$
Now, let count(n)
be the number of ways to place tiles on nx4
grid, then the recurrence is:
count(n) = count(n-1) + count(n-4)
- Base cases:
count(1) = count(2) = count(3) = 1
,count(4) = 2
Approach
Use dynamic programming to build up the solution from the base cases, storing the number of ways for each grid size up to n
.
Code
|
|
|
|
|
|