给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
(力扣原题)
题解:
精确覆盖的条件:
-
所有矩形的面积和等于最后矩形的面积。
-
除最后形成的矩形四个顶点外,其余的小矩形的顶点都应该有重合且为偶数个(2或4)。
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
long area = 0;
int minX = rectangles[0][0], minY = rectangles[0][1], maxX = rectangles[0][2], maxY = rectangles[0][3];
Map<Point, Integer> cnt = new HashMap<Point, Integer>();
for (int[] rect : rectangles) {
int x = rect[0], y = rect[1], a = rect[2], b = rect[3];
//记录所有小矩形的总面积
area += (long) (a - x) * (b - y);
//记录最终大矩形的4个顶点
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, a);
maxY = Math.max(maxY, b);
Point point1 = new Point(x, y);
Point point2 = new Point(x, b);
Point point3 = new Point(a, y);
Point point4 = new Point(a, b);
//利用map记录每个顶点出现的次数
cnt.put(point1, cnt.getOrDefault(point1, 0) + 1);
cnt.put(point2, cnt.getOrDefault(point2, 0) + 1);
cnt.put(point3, cnt.getOrDefault(point3, 0) + 1);
cnt.put(point4, cnt.getOrDefault(point4, 0) + 1);
}
//找到最终大矩形的四个顶点
Point pointMinMin = new Point(minX, minY);
Point pointMinMax = new Point(minX, maxY);
Point pointMaxMin = new Point(maxX, minY);
Point pointMaxMax = new Point(maxX, maxY);
//判断面积是否相等以及4个顶点的个数是否为1
if (area != (long) (maxX - minX) * (maxY - minY) || cnt.getOrDefault(pointMinMin, 0) != 1 || cnt.getOrDefault(pointMinMax, 0) != 1 || cnt.getOrDefault(pointMaxMin, 0) != 1 || cnt.getOrDefault(pointMaxMax, 0) != 1) {
return false;
}
//将四个顶点取出
cnt.remove(pointMinMin);
cnt.remove(pointMinMax);
cnt.remove(pointMaxMin);
cnt.remove(pointMaxMax);
//判断剩下顶点个数是否为2或4
for (Map.Entry<Point, Integer> entry : cnt.entrySet()) {
int value = entry.getValue();
if (value != 2 && value != 4) {
return false;
}
}
return true;
}
}
//自定义point类用来储存顶点坐标
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return x + y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point point2 = (Point) obj;
return this.x == point2.x && this.y == point2.y;
}
return false;
}
}