Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
![](https://leetcode.com/static/images/problemset/rectangle_perfect.gif)
Example 1:
rectangles = [ [1,1,3,3], [3,1,4,2], [3,2,4,4], [1,3,2,4], [2,3,3,4] ] Return true. All 5 rectangles together form an exact cover of a rectangular region.
![](https://leetcode.com/static/images/problemset/rectangle_separated.gif)
Example 2:
rectangles = [ [1,1,2,3], [1,3,2,4], [3,1,4,2], [3,2,4,4] ] Return false. Because there is a gap between the two rectangular regions.
![](https://leetcode.com/static/images/problemset/rectangle_hole.gif)
Example 3:
rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [3,2,4,4] ] Return false. Because there is a gap in the top center.
![](https://leetcode.com/static/images/problemset/rectangle_intersect.gif)
Example 4:
rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [2,2,4,4] ] Return false. Because two of the rectangles overlap with each other.
判断是否是完美矩形。
参考点击打开链接。转变为求三种节点的特征是否满足一定条件。
程序如下所示:
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
int len = rectangles.length;
Set<String> set = new HashSet<>();
int x1 = Integer.MAX_VALUE;
int y1 = x1;
int x2 = Integer.MIN_VALUE, y2 = x2;
int area = 0;
for (int i = 0; i < len; ++ i){
x1 = Math.min(x1, rectangles[i][0]);
y1 = Math.min(y1, rectangles[i][1]);
x2 = Math.max(x2, rectangles[i][2]);
y2 = Math.max(y2, rectangles[i][3]);
area += (rectangles[i][0] - rectangles[i][2])*(rectangles[i][1] - rectangles[i][3]);
String angle0 = rectangles[i][0] + " " + rectangles[i][1];
String angle1 = rectangles[i][0] + " " + rectangles[i][3];
String angle2 = rectangles[i][2] + " " + rectangles[i][3];
String angle3 = rectangles[i][2] + " " + rectangles[i][1];
if (!set.add(angle0)) {
set.remove(angle0);
}
if (!set.add(angle1)) {
set.remove(angle1);
}
if (!set.add(angle2)) {
set.remove(angle2);
}
if (!set.add(angle3)) {
set.remove(angle3);
}
}
if ((x1 - x2)*(y1 - y2) != area){
return false;
}
String angle0 = x1 + " " + y1;
String angle1 = x1 + " " + y2;
String angle2 = x2 + " " + y2;
String angle3 = x2 + " " + y1;
if (!set.contains(angle0)||!set.contains(angle1)||!set.contains(angle2)||!set.contains(angle3)||set.size() != 4){
return false;
}
return true;
}
}