leetcode 391. Perfect Rectangle

我们有 N 个与坐标轴对齐的矩形, 其中 N > 0, 判断它们是否能精确地覆盖一个矩形区域。

每个矩形用左下角的点和右上角的点的坐标来表示。例如, 一个单位正方形可以表示为 [1,1,2,2]。 ( 左下角的点的坐标为 (1, 1) 以及右上角的点的坐标为 (2, 2) )。




示例1

rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [3,2,4,4],
  [1,3,2,4],
  [2,3,3,4]
]

返回 true。5个矩形一起可以精确地覆盖一个矩形区域。
示例2
rectangles = [
  [1,1,2,3],
  [1,3,2,4],
  [3,1,4,2],
  [3,2,4,4]
]

返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
示例3
rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [3,2,4,4]
]

返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
示例4
rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [2,2,4,4]
]

返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def isRectangleCover(self, rectangles):
#large rectangle area is equal to small rectangles
#large rectangle points in small rectangles points
if len(rectangles) == 0 or len(rectangles[0]) == 0:
return False
x1 = float("inf")
y1 = float("inf")
x2 = 0
y2 = 0
rec = set()
area = 0
for points in rectangles:
x1 = min(points[0],x1)
y1 = min(points[1],y1)
x2 = max(points[2],x2)
y2 = max(points[3],y2)
area += (points[3]-points[1])*(points[2]-points[0])
rec.remove((points[0],points[3])) if (points[0],points[3]) in rec else rec.add((points[0],points[3]))
rec.remove((points[0],points[1])) if (points[0],points[1]) in rec else rec.add((points[0],points[1]))
rec.remove((points[2],points[3])) if (points[2],points[3]) in rec else rec.add((points[2],points[3]))
rec.remove((points[2],points[1])) if (points[2],points[1]) in rec else rec.add((points[2],points[1]))
if (x1,y2) not in rec or (x2,y1) not in rec or (x1,y1) not in rec or (x2,y2) not in rec or len(rec) != 4:
return False
return area == (y2-y1)*(x2-x1)