![]() |
VOOZH | about |
Give an n x m grid, the task is to count the number of ways you can fill an n x m grid using 1 x 2 and 2 x 1 tiles. Output the number of ways modulo 109 + 7.
Examples:
Input: n=2, m=2
Output: 2Input: n=4, m=7
Output: 781
Approach:
The idea is to solve the problem using DP with bitmasking. We'll process the grid cells column-by-column and since the number of rows can be at max 10, we can use bitmasking only on columns. It can also be observed that while filling a particular column, if we place a (1×2) tile at a cell of one column, the cell of that corresponding row in the next column also gets tiled. So now let's define our dp state:
dp[i][mask] = number of ways to fill the remaining grid from ith column to mth column such that the ith column arrangement due to (i-1)th column is represented by mask.
Now while filling the ith column we can apply the following strategy. Since some of the cells of the current columns are already filled due to previous column, we will fill only those cells which are empty. Now for the cell (j, i) if it is empty, we can fill it using a 1x2 tile or using a 2x1 tile if cell (j+1,i) is also empty. If we are using a 1x2 tile, it is also filling the corresponding row of next column, so we have to make sure that we are updating the mask for the column (i+1) accordingly while filling the ith column. Also we have to make sure when all the columns are filled then the mask generated for the next column is 0, otherwise that won't be a valid way to fill the grid.
Follow the steps to solve the problem:
i represents the Current column being processed and mask represents current mask representing the state of filled cells in the current column.i reaches m, check if the entire grid is filled (mask == 0). Return 1 if true, otherwise return 0.generateNextMask, this function generates the next possible mask based on the current mask and position in the grid by doing the following:j reaches n, add the new_mask to the nextMask vector.i with the given mask.Below is the implementation of above approach:
2
Time Complexity: O(2n * n * m)
Auxiliary Space: O(2n * n * m)