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)).
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.
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.
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.
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.
思路:遍历一遍所有的矩形,得到所有矩形的最大轮廓,在遍历过程中记录矩形的四个顶点构成的坐标出现的次数,如果是完美矩形,则这些顶点出现的次数出轮廓顶点外会出现偶数次,轮廓顶点出现一次
public boolean isRectangleCover(int[][] rectangles) {
int top=rectangles[0][2];
int right=rectangles[0][3];
int left=rectangles[0][1];
int bottom=rectangles[0][0];
HashSet<String> set = new HashSet<String>();
int area=0;
for(int[] rectangle:rectangles){
top=Math.max(top,rectangle[2]);
right=Math.max(right,rectangle[3]);
left=Math.min(left,rectangle[1]);
bottom=Math.min(bottom,rectangle[0]);
String s1 = rectangle[0] + " " + rectangle[1];
String s2 = rectangle[0] + " " + rectangle[3];
String s3 = rectangle[2] + " " + rectangle[3];
String s4 = rectangle[2] + " " + rectangle[1];
area+=(rectangle[2]-rectangle[0])*(rectangle[3]-rectangle[1]);
if (!set.add(s1)) set.remove(s1);
if (!set.add(s2)) set.remove(s2);
if (!set.add(s3)) set.remove(s3);
if (!set.add(s4)) set.remove(s4);
}
if (!set.contains(bottom + " " + left) || !set.contains(bottom + " " + right) || !set.contains(top + " " + left) || !set.contains(top + " " + right) || set.size() != 4) return false;
return area==(top-bottom)*(right-left);
}