简体   繁体   中英

How to list all points in the union of rectangles

If we define a rectangle (x1,y1), (x2,y2) by its top left and bottom right hand corners and assume that all points are integer valued, I would l like to list all points in the union of a number of rectangles.

For one rectangle, the following function returns all the points within it.

def findpoints(x1,y1,x2,y2):
    return [(x,y) for x in xrange(x1,x2+1) for y in xrange(y1,y2+1)]

I can find all the points in the union of two rectangles by,

set(findpoints(x1,y1,x2,y2)) | set(findpoints(x3,y3,x4,y4))

However I have a lot of rectangles and this is potentially very inefficient. For example, imagine if all the rectangles were almost identical. Is there a fast way of doing this?

I agree with StoryTeller but I think it is better to write it in more detail so it is understandable even for those of us with poor English skills

  1. compute the minimal rectangle which is the overlapped area of all rectangles to test

    • x1 = max (rec[i].x1)
    • y1 = max (rec[i].y1)
    • x2 = min (rec[i].x2)
    • y2 = min (rec[i].y2)
    • i=0,... all rectangles -1
    • if x1>x2 or y1>y2 then all rectangles do not overlap and so no points are inside
  2. test all points only against this new rectangle (x1,y1,x2,y2)

    • if (x>=x1) and (x<=x2) and (y>=y1) and (y<=y2) then point(x,y) is inside

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM