问题
I encountered the following problem in my programming book which I could not solve:
Given a nxm grid, write a recursive algorithm to find the number of ways that this grid could be filled by 3x1 and 1x3 blocks.
My logic for 3 x M grids:
Find the number of block combinations that could be used to fill side M of the grid.
I do not know how to change the logic to solve the question above.
Could someone please advise? Thanks.
回答1:
Let position be the upper left corner, and thereafter the first unfilled slot of the grid (left to right then top to bottom). There are up to two ways to place a block at postion. Try placing a 1x3 horizontal block at position, and call the recursive function on the remaining grid. Try placing a 3x1 vertical block at position, and call the recursive function on that. Observe that if there is no legal way to place a block (at the end, for instance, say there are is only a 2x2 square left), this branch of the program failed to find a solution. That's because the grid has to be filled by 3x1 blocks.
Your logic isn't recursive - it's a combinatorial approach, trying to count. But as long a the grid isn't huge, the computer has enough memory to actually try all the combinations. If you could relate this approach to other problems solved recursively in the book that would be great.
Here's an idea of the method signature
int blockFillings(boolean[][] grid, int posx, int posy)
来源:https://stackoverflow.com/questions/19760755/number-of-ways-to-fill-a-nxm-grid