克鲁斯卡尔算法
一、问题引出
二、介绍
三、代码实现
package com.achang.algorithm;
import java.util.Arrays;
public class Kruskal {
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},
};
Kruskal kruskal = new Kruskal(vertexs, matrix);
kruskal.list();
EData[] edges = kruskal.getEdges();
System.out.println(Arrays.toString(edges));
System.out.println("===========排序后");
kruskal.sortEData(edges);
System.out.println(Arrays.toString(edges));
System.out.println("===========");
kruskal.kruskal();
}
public Kruskal(char[] vertexs, int[][] matrix) {
int vLen = vertexs.length;
this.vertexs = vertexs;
this.matrix = matrix;
for (int i = 0; i < vLen; i++) {
for (int j = i + 1; j < vLen; j++) {
if (this.matrix[i][j] != INF) {
edgeNum++;
}
}
}
}
public void kruskal(){
int index = 0 ;
int[] ends = new int[edgeNum];
EData[] result = new EData[edgeNum];
EData[] edges = getEdges();
sortEData(edges);
for (int i = 0; i < edges.length; i++) {
int p1 = getPosition(edges[i].start);
int p2 = getPosition(edges[i].end);
int m = getEnd(ends,p1);
int n = getEnd(ends,p2);
if (m != n){
ends[m] = n;
result[index++] = edges[i];
}
}
System.out.println("最小生成树:"+Arrays.toString(result));
}
public void list() {
System.out.println("邻接矩阵为:\n");
for (int[] ints : matrix) {
System.out.println(Arrays.toString(ints));
}
}
public void sortEData(EData[] eDatas) {
for (int i = 0; i < eDatas.length - 1; i++) {
for (int j = 0; j < eDatas.length - 1 - i; j++) {
if (eDatas[j].weight > eDatas[j + 1].weight) {
EData temp = eDatas[j];
eDatas[j] = eDatas[j + 1];
eDatas[j + 1] = temp;
}
}
}
}
private int getPosition(char ch) {
for (int i = 0; i < vertexs.length; i++) {
if (vertexs[i] == ch) {
return i;
}
}
return -1;
}
private EData[] getEdges() {
int index = 0;
EData[] eDatas = new EData[edgeNum];
for (int i = 0; i < vertexs.length; i++) {
for (int j = i + 1; j < vertexs.length; j++) {
if (matrix[i][j] != INF) {
eDatas[index++] = new EData(vertexs[i], vertexs[j], matrix[i][j]);
}
}
}
return eDatas;
}
private int getEnd(int[] ends, int i) {
while (ends[i] != 0) {
i = ends[i];
}
return i;
}
}
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【star=t[" + start + "],end=[" + end + "],weight=[" + weight + "]】";
}
}
|