多边形合并、多边形融合算法实现。[C++]
任务如下图所示:
输入为蓝色五个多边形,输出为红色三个多边形,调用boost库实现。
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometry.hpp>
using BoostPoint = boost::geometry::model::d2::point_xy<double>;
using BoostPolygon = boost::geometry::model::polygon<BoostPoint>;
using BoostBox = boost::geometry::model::box<BoostPoint>;
// An highlighted block
std::vector<BoostPolygon> mergeBoxes2PointArrayVec(const std::vector<BoostPolygon> &polygons) {
std::vector<BoostPolygon> polygonsRes;
std::vector<bool> merged(polygons.size(), false); // mark polygon.
for (std::size_t i = 0; i < polygons.size(); ++i) {
if (merged[i]) continue; // skip polygon which has been merged.
BoostPolygon currentPolygon = polygons[i];
bool hasMerged = false;
for (std::size_t j = i + 1; j < polygons.size(); ++j) {
if (merged[j]) continue;
// check polygons intersects
if (boost::geometry::intersects(currentPolygon, polygons[j]) ||
boost::geometry::touches(currentPolygon, polygons[j])) {
std::vector<BoostPolygon> unionResult;
boost::geometry::union_(currentPolygon, polygons[j], unionResult);
if (!unionResult.empty()) {
currentPolygon = unionResult[0]; // return one polygon.
}
merged[j] = true; // mark this polygon.
hasMerged = true;
}
}
polygonsRes.push_back(currentPolygon);
merged[i] = hasMerged;
}
return polygonsRes;
}