链接:https://leetcode.com/problems/perfect-rectangle/description/
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.
思路:
two rules:
- The sum of rectangles' area must equal to the final rectangle
- No overlap (Edge points exist 1 times)
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
int area = 0, bot_x = INT_MAX, bot_y = INT_MAX, top_x = INT_MIN, top_y = INT_MIN;
unordered_map<int, unordered_map<int, int>> mp;
for (auto& rec : rectangles) {
int x1 = rec[0], y1 = rec[1], x2 = rec[2], y2 = rec[3];
area += (y2 - y1) * (x2 - x1);
mp[x1][y1]++;
mp[x2][y2]++;
mp[x1][y2]++;
mp[x2][y1]++;
bot_x = min(bot_x, x1);
bot_y = min(bot_y, y1);
top_x = max(top_x, x2);
top_y = max(top_y, y2);
}
if ((top_x - bot_x) * (top_y - bot_y) != area) { // area judge
return false;
}
// 四个角的点只会出现奇数次,其它的点会出现偶数次
for (auto& i : mp) {
for (auto& j : i.second) {
if ((i.first == bot_x || i.first == top_x) && (j.first == bot_y || j.first == top_y) && j.second != 1)
return false; // edge points can only exist 1 times
if (j.second & 1) { // points which exist even times must be edge points
if ((i.first == bot_x || i.first == top_x) && (j.first == bot_y || j.first == top_y))
continue;
return false;
}
}
}
return true;
}
};