forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
perfect-rectangle.cpp
49 lines (45 loc) · 1.86 KB
/
perfect-rectangle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
enum Location {L = 0, B = 1, R = 2, T = 3};
int left = numeric_limits<int>::max(), bottom = numeric_limits<int>::max(),
right = numeric_limits<int>::min(), top = numeric_limits<int>::min();
for (const auto& rect : rectangles) {
left = min(left, rect[L]);
bottom = min(bottom, rect[B]);
right = max(right, rect[R]);
top = max(top, rect[T]);
}
using P = pair<pair<int, int>, int>;
enum Corner {LB = 1, RB = 2, LT = 4, RT = 8};
unordered_map<int, unordered_map<int, int>> corner_count;
vector<P> corners{{{L, B}, LB}, {{R, B}, RB}, {{L, T}, LT}, {{R, T}, RT}};
for (const auto& rect : rectangles) {
for (const auto& corner : corners) {
const auto x = rect[corner.first.first];
const auto y = rect[corner.first.second];
if (corner_count[x][y] & corner.second) {
return false;
}
corner_count[x][y] |= corner.second;
}
}
bitset<16> is_valid;
is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true;
for (auto itx = corner_count.cbegin(); itx != corner_count.cend(); ++itx) {
const auto x = itx->first;
for (auto ity = itx->second.cbegin(); ity != itx->second.cend(); ++ity) {
const auto y = ity->first;
const auto mask = ity->second;
if ((left < x && x < right) || (bottom < y && y < top)) {
if (!is_valid[mask]) {
return false;
}
}
}
}
return true;
}
};