using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CheckServer { public class DBSCAN { private double eps; private int minPts; private List dataset; bool[] visited; /// /// /// /// 邻域半径 /// 邻域内最小点数 /// 数据集 public DBSCAN(double eps, int minPts, List dataset) { this.eps = eps; this.minPts = minPts; this.dataset = dataset; } public List Run() { int n = dataset.Count; visited = new bool[n]; List cluster = new List(); for (int i = 0; i < n; i++) { if (!visited[i]) { List neighbors = RegionQuery(i); if (neighbors.Count < minPts) { visited[i] = true; } else { cluster.Add(ExpandCluster(i, neighbors)); } } } return cluster; } //查询给定点邻域内所有点 private List RegionQuery(int i) { List neighbors = new List(); for (int j = 0; j < dataset.Count; j++) { if (i != j && Distance(dataset[i], dataset[j]) <= eps) { neighbors.Add(j); } } return neighbors; } //扩展簇 private int ExpandCluster(int i, List neighbors) { int clusterId = i; visited[i] = true; List seeds = new List(neighbors); while (seeds.Count > 0) { int current = seeds[0]; seeds.RemoveAt(0); List currentNeighbors = RegionQuery(current); if (currentNeighbors.Count >= minPts) { foreach (var neighbor in currentNeighbors) { if (!visited[neighbor]) { seeds.Add(neighbor); } } } if (!visited[current]) { visited[current] = true; clusterId = current; } } return clusterId; } private double Distance(double[] a, double[] b) { double sum = 0; for (int i = 0; i < a.Length; i++) { sum += Math.Pow(a[i] - b[i], 2); } return Math.Sqrt(sum); } } }