题目描述
有一堆box,若干个box有交集就是一个簇,求每个cluster中box的个数。注意:可以自定义box的结构体, 无需考虑旋转角度。
请用C+实现上述代码
#include <vector>
#include <queue>
#include <algorithm>
struct Box {
int x1, y1, x2, y2;
};
bool isIntersect(const Box& a, const Box& b) {
return !(a.x2 < b.x1 || a.x1 > b.x2 || a.y2 < b.y1 || a.y1 > b.y2);
}
int main() {
std::vector<Box> boxes = {/* 输入box数据 */};
std::vector<std::vector<int>> clusters;
std::vector<bool> visited(boxes.size(), false);
for (int i = 0; i < boxes.size(); ++i) {
if (visited[i]) continue;
std::queue<int> q;
q.push(i);
visited[i] = true;
std::vector<int> cluster;
while (!q.empty()) {
int j = q.front();
q.pop();
cluster.push_back(j);
for (int k = 0; k < boxes.size(); ++k) {
if (visited[k] || !isIntersect(boxes[j], boxes[k])) continue;
q.push(k);
visited[k] = true;
}
}
clusters.push_back(cluster);
}
for (const auto& cluster : clusters) {
std::cout << "Cluster size: " << cluster.size() << std::endl;
}
return 0;
}