We have already discussed the Greedy approach to solve this problem in previous article. But the previous approach doesn’t always work. For example, it fails for the above first test case. So, in this article we solve this problem using Dynamic Programming.
We know that if we want to cut minimum number of squares from the paper then we would have to cut largest square possible from the paper first and largest square will have same side as smaller side of the paper. For example if paper have the size 13 x 29, then maximum square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = 2). Now remaining paper will have size 3 x 13. Similarly we can cut remaining paper by using 4 squares of size 3 x 3 and 3 squares of 1 x 1. So minimum 9 squares can be cut from the Paper of size 13 x 29.
Explanation: minimumSquare is a function which tries to split the rectangle at some position. The function is called recursively for both parts. Try all possible splits and take the one with minimum result. The base case is when both sides are equal i.e the input is already a square, in which case the result is We are trying to find the cut which is nearest to the center which will lead us to our minimum result.
Assuming we have a rectangle with width is N and height is M.
if (N == M), so it is a square and nothing need to be done.
Otherwise, we can divide the rectangle into two other smaller one (N – x, M) and (x, M), so it can be solved recursively.
Similarly, we can also divide it into (N, M – x) and (N, x)
Also we need to be aware of an edge case here which is N=11 and M=13 or vice versa. The following will be the best possible answer for the given test case:
Our Approach will return 8 for this case but as you can see we can cut the paper in 6 squares which is minimum. This happens because there is no vertical or horizontal line that cuts through the whole square in the optimum solution.
Below is the implementation of the above idea using Dynamic Programming.
This article is contributed by Ayush Govil, Aditya Nihal Kumar Singh and Deepanshu Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...