DBSCAN算法c++
时间: 2023-11-25 14:51:24 浏览: 64
以下是使用C++实现DBSCAN算法的示例代码:
```c++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point {
double x, y;
int cluster;
};
double distance(Point a, Point b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
vector<Point> get_neighbors(vector<Point> points, Point center, double eps) {
vector<Point> neighbors;
for (int i = 0; i < points.size(); i++) {
if (distance(points[i], center) <= eps) {
neighbors.push_back(points[i]);
}
}
return neighbors;}
void expand_cluster(vector<Point>& points, Point center, int cluster, double eps, int minPts) {
center.cluster = cluster;
vector<Point> neighbors = get_neighbors(points, center, eps);
if (neighbors.size() < minPts) {
return;
}
for (int i = 0; i < neighbors.size(); i++) {
if (neighbors[i].cluster == -1) {
neighbors[i].cluster = cluster;
}
else if (neighbors[i].cluster == 0) {
neighbors[i].cluster = cluster;
expand_cluster(points, neighbors[i], cluster, eps, minPts);
}
}
}
void dbscan(vector<Point>& points, double eps, int minPts) {
int cluster = 0;
for (int i = 0; i < points.size(); i++) {
if (points[i].cluster != 0) {
continue;
}
vector<Point> neighbors = get_neighbors(points, points[i], eps);
if (neighbors.size() < minPts) {
points[i].cluster = -1;
}
else {
cluster++;
expand_cluster(points, points[i], cluster, eps, minPts);
}
}
}
int main() {
vector<Point> points = {{1, 2}, {2, 1}, {2, 3}, {3, 2}, {8, 9}, {9, 8}, {9, 10}, {10, 9}};
dbscan(points, 2, 2);
for (int i = 0; i < points.size(); i++) {
cout << "(" << points[i].x << ", " << points[i].y << "): " << points[i].cluster << endl;
}
return 0;
}
```
阅读全文