四叉树的c++代码
时间: 2023-09-26 08:09:23 浏览: 94
以下是关于四叉树的C++代码:
```cpp
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
};
class QuadTree {
private:
Point topLeft;
Point bottomRight;
QuadTree* NW;
QuadTree* NE;
QuadTree* SW;
QuadTree* SE;
bool isLeaf;
int value;
public:
QuadTree(Point tl, Point br) {
topLeft = tl;
bottomRight = br;
isLeaf = true;
value = 0;
NW = nullptr;
NE = nullptr;
SW = nullptr;
SE = nullptr;
}
void insert(Point p) {
if (p.x < topLeft.x || p.x > bottomRight.x || p.y < topLeft.y || p.y > bottomRight.y) {
return;
}
if (isLeaf) {
if (value == 0) {
value = 1;
}
if (topLeft.x == bottomRight.x && topLeft.y == bottomRight.y) {
return;
}
int xMid = (topLeft.x + bottomRight.x) / 2;
int yMid = (topLeft.y + bottomRight.y) / 2;
NW = new QuadTree(Point(topLeft.x, topLeft.y), Point(xMid, yMid));
NE = new QuadTree(Point(xMid + 1, topLeft.y), Point(bottomRight.x, yMid));
SW = new QuadTree(Point(topLeft.x, yMid + 1), Point(xMid, bottomRight.y));
SE = new QuadTree(Point(xMid + 1, yMid + 1), Point(bottomRight.x, bottomRight.y));
isLeaf = false;
}
NW->insert(p);
NE->insert(p);
SW->insert(p);
SE->insert(p);
}
bool contains(Point p) {
if (p.x < topLeft.x || p.x > bottomRight.x || p.y < topLeft.y || p.y > bottomRight.y) {
return false;
}
if (isLeaf) {
return true;
}
return NW->contains(p) || NE->contains(p) || SW->contains(p) || SE->contains(p);
}
};
int main() {
QuadTree qt(Point(0, 0), Point(100, 100));
qt.insert(Point(10, 10));
qt.insert(Point(30, 30));
qt.insert(Point(50, 50));
qt.insert(Point(70, 70));
qt.insert(Point(90, 90));
cout << qt.contains(Point(10, 10)) << endl; // true
cout << qt.contains(Point(20, 20)) << endl; // true
cout << qt.contains(Point(30, 30)) << endl; // true
cout << qt.contains(Point(40, 40)) << endl; // true
cout << qt.contains(Point(50, 50)) << endl; // true
cout << qt.contains(Point(60, 60)) << endl; // true
cout << qt.contains(Point(70, 70)) << endl; // true
cout << qt.contains(Point(80, 80)) << endl; // true
cout << qt.contains(Point(90, 90)) << endl; // true
cout << qt.contains(Point(100, 100)) << endl; // false
return 0;
}
```
这是一个简单的四叉树实现,用于存储点并支持点的查询。在这个实现中,每个节点最多可以存储一个点,当一个节点存储的点数大于1时,它会被细分为四个子节点。
阅读全文