假设我有一堆矩形,其中一些相交,一些孤立。例如
+--------------- + +-------- + | | | | | | | | | A | | C | | +---------------- + | | | | | | +---------+-------- + | | | | | | +---------|----- + B | | D | | | | | | | +------------------ + +---------------- + +------------------ + +-------- + | | | | | E | | X | +-------------------+ | | | | +-------- + | | +------------ + | | | | | F | | | | | | Y | | | | | +-------------------+ +------------ +
Rect A, B intersect with each other, C, D have one same point, E, F have two same points, X, Y are isolated.
I have two questions:
- How to partion these rectangles into rectangles which cover A, B, C, D, E, F, X, Y exactly also have minimum count like this:
+---------+----- + +-------- + | | | | | | | | | | | | | | | | | +--------- + | | | | | | +---------+-------- + | | | | | | +---------+ | | | | | | | | | | | | +-------------------+ +------+----------+ +------------------ + +-------- + | | | | | | | | | | | | | | +---------+ | | +------------ + | | | | | | | | | | | | | | | | +-------------------+ +-------------+
- How to cover intersected rectangles with big ones? Like this:
+---------------------------+ +-------------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-------------------+ +---------------------------+ +-------------------+ +---------+ | | | | | | | | | | | | | | +---------+ | | +------------ + | | | | | | | | | | | | | | | | +-------------------+ +-------------+
For Q1, I've no idea at all....For Q2, I wrote some code in C++ but have poor efficiency. I believe there're better methods/algorithm.
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;
}
}
最佳答案
这是算法:http://goo.gl/aWDJo
您可以阅读有关查找凸包算法的信息:http://ralph.cs.cf.ac.uk/papers/Geometry/boxing.pdf