import java.util.Arrays;
public class Kurskal {
private int edgeNum;
private char[] vertexs;
private int[][] matrix;
private static final int INF = Integer.MAX_VALUE;
public static void main(String[] args) {
char[] vertexs = {
'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int[][] matrix = {
{
0, 12, INF, INF, INF, 16, 14},
{
12, 0, 10, INF, INF, 7, INF},
{
INF, 10, 0, 3, 5, 6, INF},
{
INF, INF, 3, 0, 4, INF, INF},
{
INF, INF, 5, 4, 0, 2, 8},
{
16, 7, 6, INF, 2, 0, 9},
{
14, INF, INF, INF, 8, 9, 0}};
Kurskal kurskal = new Kurskal(vertexs, matrix);
kurskal.print();
EData[] eData = kurskal.getEData();
System.out.println(Arrays.toString(eData));
System.out.println("克鲁斯卡尔法求最小生成树后:");;
kurskal.kruskal();
}
public Kurskal(char[] nVertexs, int[][] nMatrix) {
vertexs = new char[nVertexs.length];
for (int i = 0; i < nVertexs.length; i++) {
vertexs[i] = nVertexs[i];
}
matrix = new int[nMatrix.length][nMatrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = nMatrix[i][j];
if (matrix[i][j] != INF && i > j) {
edgeNum++;
}
}
}
}
public void print() {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
private void sortEdges(EData[] edges) {
for (int i = 0; i < edges.length - 1; i++) {
for (int j = 0; j < edges.length - 1 - i; j++) {
if (edges[j].weight > edges[j + 1].weight) {
EData temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
}
private int getPosition(char c) {
for (int i = 0; i < vertexs.length; i++) {
if (vertexs[i] == c) {
return i;
}
}
return -1;
}
private EData[] getEData() {
int index = 0;
EData[] edges = new EData[edgeNum];
for(int i=0;i<matrix.length;i++){
for(int j=i+1;j<matrix[0].length;j++){
if(matrix[i][j] != INF){
edges[index++] = new EData(vertexs[i],vertexs[j],matrix[i][j]);
}
}
}
return edges;
}
private int getEnd(int[] ends, int i) {
while(ends[i] != 0) {
i = ends[i];
}
return i;
}
private void kruskal(){
int index = 0;
int[] end = new int[edgeNum];
EData[] res = new EData[vertexs.length-1];
EData[] edges = getEData();
sortEdges(edges);
for(int i=0;i<edgeNum;i++){
int p1 = getPosition(edges[i].start);
int p2 = getPosition(edges[i].end);
int end1 = getEnd(end, p1);
int end2 = getEnd(end, p2);
if(end1 != end2){
end[end1] = end2;
res[index++] = edges[i];
}
}
System.out.println(Arrays.toString(res));
}
}
class EData {
char start;
char end;
int weight;
public EData(char start, char end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
@Override
public String toString() {
return "EData{" +
"<" + start +
", " + end +
"> " + weight +
'}';
}
}