Number of ways to fill a nxm grid

南楼画角 提交于 2019-12-24 15:31:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!