Prime算法
public int prime(int[][] map, int v0, int n) { // v0为起始节点,n为节点个数
int[] lowCost = new int[n]; // 最小距离
boolean[] st = new boolean[n]; // 是否确定
int v = v0, t = v0, min, sum = 0;
for (int i = 0; i < n; i++) {
lowCost[i] = map[v0][i];
}
st[v0] = true;
for (int i = 0; i < n - 1; i++) {
min = 0x3f3f3f3f;
for (int j = 0; j < n; j++) { // 选取最小未入边对应的节点
if(!st[j]&&lowCost[j]<min){
min = lowCost[j];
t = j;
}
}
st[t] = true;
v = t;
sum +=min;
for (int j = 0; j < n; j++) {
if(!st[j]&&map[v][j]<lowCost[j]){
lowCost[j] = map[v][j];
}
}
}
return sum;
}
迪杰斯特拉
public static int[] dij(int n,int[][] map,int v0,int[] path,int[] dist){
final int inf = 0x3f3f3f3f;
boolean[] st = new boolean[n];
int min , t = 0;
for (int i = 0; i < n; i++) {
dist[i] = map[v0][i];
if(map[v0][i]<inf){
path[i] = v0;
}else{
path[i] = -1;
}
}
st[v0] = true;
path[v0] = -1;
dist[v0] = 0;
for (int i = 0; i < n-1; i++) {
min = inf;
for (int j = 0; j < n; j++) {
if(!st[j]&&dist[j]<min){
min = dist[j];
t = j;
}
}
st[t] = true;
for (int j = 0; j < n; j++) {
if(!st[j]&&dist[t]+map[t][j]<dist[j]){
dist[j] = dist[t]+map[t][j];
path[j] = t;
}
}
}
return dist;
}