Is there any problem in @src/maxemptyrects.cpp ? --- Content from referenced files ---…
- User
Is there any problem in @src/maxemptyrects.cpp ? --- Content from referenced files --- Content from @C:\routenodes\src\maxemptyrects.cpp: // 极大空矩形
#include #include #include
#include "routenodes.hpp"
namespace routenodes {
// 扫描线算法中的事件类型 enum class ScanEventType { Start, End, };
// 扫描线算法中的事件 struct ScanEvent { float x; float y1; float y2; ScanEventType type;
code// 当两个事件的x坐标相同时,先处理开始事件,再处理结束事件 bool operator<(const ScanEvent& other) const { if (x != other.x) { return x < other.x; } return type < other.type; }};
// 沿一个方向的区间 struct Interval { float y1; float y2;
code// 只有两个区间不重叠时才视为有序 bool operator<(const Interval& other) const { return y2 <= other.y1; }};
// 用扫描线算法求所有极大空矩形 // 已知矩形所用的坐标系为left < right, top < bottom,且互不重叠 void findMaxEmptyRects(const std::vector& inRects, const float canvasWidth, const float canvasHeight, std::vector& outRects) { std::vector events; events.push_back({canvasWidth, 0.0f, canvasHeight, ScanEventType::Start}); for (const auto& rect : inRects) { events.push_back({rect.left, rect.top, rect.bottom, ScanEventType::Start}); events.push_back({rect.right, rect.top, rect.bottom, ScanEventType::End}); }
codestd::sort(events.begin(), events.end()); std::set<Interval> occupiedIntervals; float previousX = 0.0f; for (const auto& event : events) { float currentX = event.x; if (previousX < currentX) { float currentY = 0.0f; for (const auto& occupiedInterval : occupiedIntervals) { if (currentY < occupiedInterval.y1) { outRects.push_back({previousX, currentX, currentY, occupiedInterval.y1}); } currentY = std::max(currentY, occupiedInterval.y2); } if (currentY < canvasHeight) { outRects.push_back({previousX, currentX, currentY, canvasHeight}); } } if (event.type == ScanEventType::Start) { occupiedIntervals.insert({event.y1, event.y2}); } else { occupiedIntervals.erase({event.y1, event.y2}); } previousX = currentX; } Assistant
Yes, there is a logical problem in
src/maxemptyrects.cppwithin theScanEvent::operator<implementation.The issue lies in the order of processing for events that occur at the same x-coordinate. The current implementation processes
Startevents beforeEndevents. This is incorrect for handling cases where rectangles are adjacent to each other.When two rectangles are horizontally adjacent, they share a vertical edge. At that x-coordinate, one rectangle ends and the other begins. The correct logic is to process the event first, removing the interval of the first rectangle, and then process the event, adding the interval for the second rectangle.