Prim
import java.util.ArrayList;
import java.util.List;
public class Prim {
int[][] map;
int[] vis;
int n;
public static void main(String[] args) {
Prim p=new Prim();
p.init();
System.out.println(p.prim());
}
void init() {
n=6;
vis=new int[n];
map= new int[][]{
{0, 6, 1, 5, 0, 0},
{6, 0, 5, 0, 3, 0},
{1, 5, 0, 5, 6, 4},
{5, 0, 5, 0, 0, 2},
{0, 3, 6, 0, 0, 6},
{0, 0, 4, 2, 6, 0}
};
}
int prim() {
List<Integer> list=new ArrayList<>();
int x=0;
int ans=0;
for (int i = 0; i < n-1; i++) {
list.add(x);
vis[x]=1;
int m=Integer.MAX_VALUE;
for (Integer j : list) {
for (int k = 0; k < n; k++) {
if(vis[k]==0) {
if(map[j][k]>0&&map[j][k]<m) {
m=map[j][k];
x=k;
}
}
}
}
ans+=m;
}
return ans;
}
}
Kruskal:
package 最小生成树;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Kruskal {
int[][] map;
int n;
List<edge> list = new ArrayList<>();
int[] parent;
int[] rank;
public static void main(String[] args) {
Kruskal p = new Kruskal();
p.init();
System.out.println(p.kruskal());
}
void init() {
n = 6;
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
map = new int[][] { { 0, 6, 1, 5, 0, 0 }, { 0, 0, 5, 0, 3, 0 }, { 0, 0, 0, 5, 6, 4 }, { 0, 0, 0, 0, 0, 2 },
{ 0, 0, 0, 0, 0, 6 }, { 0, 0, 0, 0, 0, 0 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] > 0) {
list.add(new edge(i, j, map[i][j]));
}
}
}
Collections.sort(list, new Comparator<edge>() {
@Override
public int compare(edge o1, edge o2) {
return o1.val - o2.val;
}
});
}
int find(int x) {
return parent[x] == x ? x : (parent[x] = find(parent[x]));
}
boolean merge(int x, int y) {
int a = find(x), b = find(y);
if (a != b) {
if (rank[a] <= rank[b])
parent[a] = b;
else
parent[b] = a;
if (rank[a] == rank[b])
rank[b]++;
return true;
}
return false;
}
int kruskal() {
int ans=0;
for (edge edge : list) {
if(merge(edge.x,edge.y)) {
ans+=edge.val;
}
}
return ans;
}
class edge {
int x;
int y;
int val;
public edge(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
public edge() {
}
}
}