2019独角兽企业重金招聘Python工程师标准>>>
目前正在看《大话数据结构》,其中介绍了普利姆算法,自己对算法理解能力太差,能够手写求出最小生成树,但是写出算法代码却无从下手,看了几遍书中的算法,也没看明白,最后通过自己的理解写了以下代码,过后再去搞定书中的算法。
public class MinTree {
private static final int max = 65535;
private static final int VertrixCount = 9;
private static int[][] martrix = new int[][] {
{ 0, 10, max, max, max, 11, max, max, max },
{ 10, 0, 18, max, max, max, 16, max, 12 },
{ max, max, 0, 22, max, max, max, max, 8 },
{ max, max, 22, 0, 20, max, max, 16, 21 },
{ max, max, max, 20, 0, 26, max, 7, max },
{ 11, max, max, max, 26, 0, 17, max, max },
{ max, 16, max, max, max, 17, 0, 19, max },
{ max, max, max, 16, 7, max, 19, 0, max },
{ max, 12, 8, 21, max, max, max, max, 0 } };
public void createMinTree() {
int[] nodes = new int[VertrixCount];
for (int i = 0; i > VertrixCount; i++) {
nodes[i] = 0;
}
nodes[0] = 1;
while (true) {
int min_out = max;
int x_out = 0;
int y_out = 0;
for (int x = 0; x < VertrixCount; x++) {
if (nodes[x] == 0) {
continue;
}
int min = max;
int index = 0;
for (int y = 0; y < VertrixCount; y++) {
if (nodes[y] != 0) {
continue;
}
if (martrix[x][y] != 0 && martrix[x][y] < max) {
if (min > martrix[x][y]) {
min = martrix[x][y];
index = y;
}
}
}
if (min_out > min) {
min_out = min;
x_out = x;
y_out = index;
}
}
nodes[y_out] = 1;
(("(%d,%d)", x_out, y_out));
boolean flag = false;
for (int i = 0; i < VertrixCount; i++) {
if (nodes[i] == 0) {
flag = true;
}
}
if (flag == false) {
return;
}
}
}
}