Cut rectangle in minimum number of squares

前端 未结 6 1458
-上瘾入骨i
-上瘾入骨i 2020-12-28 17:29

I\'m trying to solve the following problem:

A rectangular paper sheet of M*N is to be cut down into squares such that:

  1. The paper i
6条回答
  •  温柔的废话
    2020-12-28 18:29

    Here is a greedy impl. As @David mentioned it is not optimal and is completely wrong some cases so dynamic approach is the best (with caching).

    def greedy(m, n):
        if m == n:
            return 1
        if m < n:
            m, n = n, m
        cuts = 0
    
        while n:
            cuts += m/n
            m, n = n, m % n
        return cuts
    
    print greedy(2, 7)
    

    Here is DP attempt in python import sys

    def cache(f):
        db = {}
    
        def wrap(*args):
            key = str(args)
            if key not in db:
                db[key] = f(*args)
            return db[key]
        return wrap
    
    
    @cache
    def squares(m, n):
        if m == n:
            return 1
        xcuts = sys.maxint
        ycuts = sys.maxint
        x, y = 1, 1
        while x * 2 <= n:
            xcuts = min(xcuts, squares(m, x) + squares(m, n - x))
            x += 1
        while y * 2 <= m:
            ycuts = min(ycuts, squares(y, n) + squares(m - y, n))
            y += 1
        return min(xcuts, ycuts)
    

提交回复
热议问题