-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfect Rectangle
More file actions
67 lines (57 loc) · 2.32 KB
/
Copy pathPerfect Rectangle
File metadata and controls
67 lines (57 loc) · 2.32 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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.
class Solution {
public:
bool checkCorners(auto& corners, int x, int y, int orient)
{
int& pt = corners[x][y];
// already with same orientation exists so overlapping rectangles exist
if(pt&orient) return false;
pt |= orient;
return true;
}
bool isRectangleCover(vector<vector<int>>& rectangles) {
enum cornrPt { BL = 1, BR = 2, TL = 4, TR = 8};
unordered_map<int, unordered_map<int, int>> corners;
int maxX = INT_MIN, maxY = INT_MIN, minX = INT_MAX, minY = INT_MAX;
for(auto& rect : rectangles)
{
maxX = max(maxX, rect[2]);
minX = min(minX, rect[0]);
maxY = max(maxY, rect[3]);
minY = min(minY, rect[1]);
if(not checkCorners(corners, rect[0], rect[1], BL)) return false;
if(not checkCorners(corners, rect[2], rect[1], BR)) return false;
if(not checkCorners(corners, rect[2], rect[3], TR)) return false;
if(not checkCorners(corners, rect[0], rect[3], TL)) return false;
}
unordered_map<int, bool> validOuterCorns{{BL, 1}, {BR, 1}, {TL, 1}, {TR, 1}}, validIntraCorns{{BL+BR, 1}, {BL+TL, 1}, {BR+TR, 1}, {TL+TR, 1}, {BL+BR+TL+TR, 1}};
for(auto& x : corners)
{
int i = x.first;
for(auto& y : x.second)
{
int j = y.first, numOfCorns = y.second;
if(((i == maxX) or (i == minX)) and ((j == maxY) or (j == minY)))
{
if(not validOuterCorns[numOfCorns]) return false;
}
else
{
cout<<numOfCorns<<endl;
if(not validIntraCorns[numOfCorns]) return false;
}
}
}
return true;
}
};