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
算法实现步骤如下:
1.先遍历每一个矩阵,对每一个点进行处理,对于每一个位置的点用hash表来存储这个位置出现了几个corner,并且为了区分出现在这个位置的点是什么编号,我们可以用一个掩码来表示这个点的编号,这样也好判断是否这个位置出现了重复的编号的corner.
2. 对矩阵做好处理之后接下来就好遍历hash表查看对于每个位置来说是否满足以上规定的点的形式.任意一个点不满足条件即可返回false.
在实现的过程中为了简化代码用了一些技巧,比如为了在hash表中保存一个坐标,可以用字符串形式来保存.还有判断一个数是否是2的倍数可以用val&(-val)是否为0来判断.
这样时间复杂度即可降为O(n)
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
unordered_map<string, int> hash;
for(auto val: rectangles)
{
for(int i = 0; i < 4; i++)
{
string tem = to_string(val[i/2*2])+','+to_string(val[i%2*2+1]);
if(hash[tem]&(1<<i)) return false;
hash[tem] |= (1<<i);
}
}
int cntCorner = 0;
for(auto& val: hash)
{
int sec = val.second;
if(!(sec&(sec-1)) && cntCorner++ > 4) return false;
if((sec&(sec-1)) && !(sec==3||sec==12||sec==5||sec==10||sec==15))
return false;
}
return true;
}
};
我自己的,忘记考虑内部情况了,还要多一个内部遍历才行。
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
int area = 0,x1 = INT_MIN, y1 = INT_MIN, x2 = INT_MAX, y2 = INT_MAX;
for(int i = 0; i < rectangles.size(); i++){
area+=(rectangles[i][2]-rectangles[i][0])*(rectangles[i][3]-rectangles[i][1]);
if(rectangles[i][1] <= y2&&rectangles[i][0]<=x2) y2 = rectangles[i][1], x2 = rectangles[i][0];
if(rectangles[i][3] >= y1&&rectangles[i][2]>=x1) y1 = rectangles[i][3], x1 = rectangles[i][2];
}
int a1 = 0, a2 = 0, a3 = 0, a4 = 0;
int b1 = x1^x2, b2 = y1^y2, b3 = x1^x2, b4 = y1^y2;
for(auto val:rectangles) {
if(val[1] == y2) a1+=val[2]-val[0],b1=b1^val[2]^val[0];
if(val[2] == x1) a2+=val[3]-val[1],b2=b2^val[3]^val[1];
if(val[3] == y1) a3+=val[2]-val[0],b3 = b3^val[2]^val[0];
if(val[0] == x2) a4+=val[3]-val[1],b4 = b4^val[3]^val[1];
}
printf("%d,%d,%d,%d",b1,b2,b3,b4);
if(b1!=0||b2!=0||b3!=0||b4!=0) return false;
//printf("%d,%d,%d,%d",a1,a2,a3,a4);
if((a1 != (x1-x2))||a1!=a3) return false;
if((a2 != (y1-y2))||a2!=a4) return false;
//cout<<area<<endl;
//printf("%d,%d,%d,%d",x1,y1,x2,y2);
if((x1-x2)*(y1-y2) == area) {
return true;
} else {
return false;
}
}
};