closeness centrality 算法java代码
时间: 2023-12-13 11:04:10 浏览: 194
Closeness-Centrality
下面是 closeness centrality 算法的 Java 代码示例:
```java
import java.util.*;
public class ClosenessCentrality {
public static void main(String[] args) {
int[][] graph = {
{0, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 1},
{0, 0, 1, 1, 0}
};
int n = graph.length;
double[] closeness = new double[n];
for (int i = 0; i < n; i++) {
closeness[i] = getClosenessCentrality(i, graph);
}
System.out.println("Closeness centrality:");
for (int i = 0; i < n; i++) {
System.out.printf("%d: %.4f\n", i, closeness[i]);
}
}
private static double getClosenessCentrality(int node, int[][] graph) {
int n = graph.length;
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[node] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()) {
int curr = queue.poll();
for (int i = 0; i < n; i++) {
if (graph[curr][i] == 1 && dist[i] == Integer.MAX_VALUE) {
dist[i] = dist[curr] + 1;
queue.offer(i);
}
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += dist[i];
}
return 1.0 / sum;
}
}
```
其中,`graph` 表示图的邻接矩阵,`n` 表示顶点数,`closeness` 存储每个顶点的 closeness centrality 值,`getClosenessCentrality` 方法计算某个顶点的 closeness centrality 值。
阅读全文