I have a set of rectangles and i need to calculate the manhatten distance between them. I already tried to implement it, but the code blow up and did not work well.
Maybe someone could help me with some smart (and efficient) formulas which could be used to calculate the distance between two rectangles?
The distance between
I suggest, you work with the central points of rectangles and rectangle widths to compute the distances. You mainly have to figure out which corners (edges) of rectangles to use for computation. everything else is simple. A quick example:
class Rect: def __init__(self,cpt,w,h): self.x = cpt self.y = cpt 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))