首页 文章

矩形之间的曼哈顿距离

提问于
浏览
1

我有一组矩形,我需要计算它们之间的manhatten距离 . 我已经尝试过实现它,但代码爆炸并且效果不佳 .

也许有人可以帮助我使用一些智能(和有效)公式,可以用来计算两个矩形之间的距离?

例子:

enter image description here

AB 之间的距离是 1 行的长度 . AC 之间的距离是 2 行的长度 . 等等

我使用python来实现一切 . 如果已经存在一个函数(例如scipy)并且有人知道它,那么这也很好 .

谢谢

1 回答

  • 3

    我建议你使用矩形和矩形宽度的中心点来计算距离 . 您主要必须弄清楚要用于计算的矩形的哪些角(边) . 其他一切都很简单 . 一个简单的例子:

    class Rect:
        def __init__(self,cpt,w,h):
            self.x = cpt[0]
            self.y = cpt[1]
            self.w = w
            self.h = h
    
        def dist(self,other):
            #overlaps in x or y:
            if abs(self.x - other.x) <= (self.w + other.w):
                dx = 0;
            else:
                dx = abs(self.x - other.x) - (self.w + other.w)
            #
            if abs(self.y - other.y) <= (self.h + other.h):
                dy = 0;
            else:
                dy = abs(self.y - other.y) - (self.h + other.h)
            return dx + dy
    
    #example:
    A = Rect((0,0),2,1)
    B = Rect((4,5),1,2)
    C = Rect((-1,-5),1,1)
    
    print(A.dist(C))
    print(A.dist(B))
    print(B.dist(C))
    

相关问题