Given an n × 4 matrix where n is a positive number, find the number of ways to fill the matrix with 1 × 4 tiles.

For example, there are 3 ways to place 1 × 4 tiles in a 5 × 4 matrix:

  1. Place all 5 tiles horizontally.
  2. Place 4 tiles vertically in the first 4 rows and 1 tile horizontally in the last row.
  3. Place 1 tile horizontally in the first row and adjust 4 tiles vertically in the remaining rows.

 
Similarly, there are 4 ways to place 1 × 4 tiles in a 6 × 4 matrix:

  1. Place all 6 tiles horizontally.
  2. Place 4 tiles vertically in the first 4 rows and the remaining 2 tiles horizontally in the last 2 rows.
  3. Place 2 tiles horizontally in the first 2 rows, and adjust the remaining 4 tiles vertically in the remaining rows.
  4. Place 2 tiles horizontally in the first and last row, and adjust the remaining 4 tiles vertically in the middle rows.

Practice this problem

 
From the above examples, it is evident that a single tile can be placed horizontally or 4 tiles can be placed together vertically (since the matrix has dimensions n × 4). So, the problem of computing the number of ways T(n) for an n × 4 matrix can be broken down into the subproblems of computing T(n-1) and T(n-4), and then adding the two.

Considering this, the recurrence relation T(n) can be written as:

T(n) = T(n-1) + T(n-4), where n > 4 and
T(1) = T(2) = T(3) = 1    // all tiles can be placed horizontally only for n <= 3
T(4) = 2                  // all tiles can be placed horizontally or vertically.

Following is the C++, Java, and Python program that implements the above recurrence:

C++


Download  Run Code

Output:

The total number of ways is 3

Java


Download  Run Code

Output:

The total number of ways is 3

Python


Download  Run Code

Output:

The total number of ways is 3

The time complexity of the proposed solution is exponential since it computes solutions to the same subproblems repeatedly, i.e., the problem exhibits overlapping subproblems.

We can easily solve this problem by using dynamic programming. The idea is to construct a temporary array that stores the results of each subproblem using already computed results of the smaller subproblems. The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The total number of ways is 3

Java


Download  Run Code

Output:

The total number of ways is 3

Python


Download  Run Code

Output:

The total number of ways is 3

The time complexity of the proposed solution is O(n) and requires O(n) extra space. We can make the program to run in constant space by storing solutions to only the last four subproblems at any point and discarding the rest. The space-efficient implementation is left as an exercise to the readers.