假设我有一堆矩形,其中一些相交,一些孤立。例如。
+--------------- + +-------- +
| | | |
| | | |
| 一个 | | C |
| +---------------- + | |
| | | | +---------+-------- +
| | | | | |
+---------|----- + B | | D |
| | | |
| | +------------------ +
+---------------- +
+-------- + +-------- +
| | | |
| E | | X |
+-------------------+ | |
| | +-------- +
| | +------------ +
| | | |
| F | | |
| | | 是 |
| | | |
+--------------------+ +------------ +
矩形 A、B 相交,C、D 有一个相同点,E、F 有两个相同点,X、Y 是孤立的。
我有两个问题:
- 如何将这些矩形划分为覆盖 A、B、C、D、E、F、X、Y 的矩形也具有这样的最小计数:
+---------+----- + +-------- +
| | | | |
| | | | |
| | | | |
| | +--------- + | |
| | | | +---------+-------- +
| | | | | |
+---------+ | | | |
| | | | |
| | | +-------------------+
+--------+----------+
+-------- + +-------- +
| | | |
| | | |
| | | |
| | +----------+
| | +------------ +
| | | |
| | | |
| | | |
| | | |
+--------------------+ +-------------+
- 如何用大矩形覆盖相交的矩形?像这样:
+---------------------------+ +------------------------+
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | +-------------------+
+---------------+
+--------------------+ +---------+
| | | |
| | | |
| | | |
| | +----------+
| | +------------ +
| | | |
| | | |
| | | |
| | | |
+--------------------+ +-------------+
对于第一季度,我完全不知道......对于第二季度,我用 C++ 编写了一些代码,但效率很差。我相信有更好的方法/算法。
bool intersectRect(const Rect& rect1, const Rect& rect2) {
/* if rect1 and rect2 intersect return true
else return false
*/
}
Rect mergeIntersectRects(const set<Rect>& rects) {
// suppose rects are all intersected. This function only return a smallest Rect that cover all rects.
}
set<Rect> mergeRectToRects(const set<Rect>& rectset, const Rect& rect) {
set<Rect> _intersect_rects;
set<Rect> _unintersect_rects;
for(set<Rect>::const_iterator it = rectset.begin();
it != rectset.end();
++it) {
if(intersectRect(*it, rect))
_intersect_rects.insert(*it);
else
_unintersect_rects.insert(*it);
}
if(!_intersect_rects.empty()) {
_intersect_rects.insert(rect);
return mergeRectToRects(_unintersect_rects,
mergeIntersectRects(_intersect_rects));
}
else {
_unintersect_rects.insert(rect);
return _unintersect_rects;
}
}