import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Mst {
public static final double NIE_JE_HRANA = Double.POSITIVE_INFINITY;
public static List<Hrana> dijkstraPrim(double[][] ms) {
return dijkstraPrim(ms, 0);
}
public static List<Hrana> dijkstraPrim(double[][] ms, int s) {
double[] hodnoty = new double[ms.length];
boolean[] vybavene = new boolean[ms.length];
int[] predchodcovia = new int[ms.length];
int pocetVybavenych = 1;
int vrchol = s;
Arrays.fill(vybavene, false);
vybavene[s] = true;
predchodcovia[s] = -1;
for (int i = 0; i < ms.length; i++)
hodnoty[i] = (i == s) ? 0 : Double.POSITIVE_INFINITY;
List<Hrana> mst = new ArrayList<Hrana>(ms.length - 1);
while (pocetVybavenych < ms.length) {
// hladam susedov vrcholu
double minHodnota = Double.POSITIVE_INFINITY;
int minIdx = -1;
for (int i = 0; i < ms.length; i++) {
if (ms[vrchol][i] == NIE_JE_HRANA || vybavene[i])
continue;
if (ms[vrchol][i] < hodnoty[i]) {
hodnoty[i] = ms[vrchol][i];
predchodcovia[i] = vrchol;
}
}
// ideme hladat vrchol s min hodnotou, ktory nie je vybaveny
for (int i = 0; i < ms.length; i++) {
if (!vybavene[i] && hodnoty[i] < minHodnota) {
minHodnota = hodnoty[i];
minIdx = i;
}
}
vybavene[minIdx] = true;
vrchol = minIdx;
pocetVybavenych++;
}
for (int i = 0; i < ms.length; i++) {
if (i == s)
continue;
mst.add(new Hrana(predchodcovia[i], i, ms[predchodcovia[i]][i]));
}
return mst;
}
public static List<Hrana> kruskal(double[][] ms) {
List<Hrana> mst = new ArrayList<Hrana>(ms.length - 1);
int[] mnoziny = new int[ms.length];
for (int i = 0; i < ms.length; i++)
mnoziny[i] = i;
Set<Hrana> hrany = new HashSet<Hrana>();
for (int i = 0; i < ms.length; i++) {
for (int j = 0; j < ms.length; j++)
if (ms[i][j] != NIE_JE_HRANA) {
hrany.add(new Hrana(i, j, ms[i][j]));
}
}
Hrana[] utriedeneHrany= hrany.toArray(new Hrana[0]);
Arrays.sort(utriedeneHrany);
for (Hrana h : utriedeneHrany) {
System.out.println(h);
if (mnoziny[h.getVrchol1()] == mnoziny[h.getVrchol2()])
continue;
mst.add(h);
int id = mnoziny[h.getVrchol2()];
for (int i = 0; i < mnoziny.length; i++)
if (mnoziny[i] == id)
mnoziny[i] = mnoziny[h.getVrchol1()];
}
return mst;
}
public static void main(String[] args) {
// double[][] ms = new double[][]
// {
// {NIE_JE_HRANA, 5, 5},
// {5, NIE_JE_HRANA, 10},
// {5, 10, NIE_JE_HRANA}
// };
double[][] ms = new double[][]
{
{NIE_JE_HRANA, 1, 2, NIE_JE_HRANA},
{1, NIE_JE_HRANA, NIE_JE_HRANA, 2},
{2, NIE_JE_HRANA, NIE_JE_HRANA, 2},
{NIE_JE_HRANA, 2, 2, NIE_JE_HRANA}
};
//List<Hrana> mst = dijkstraPrim(ms);
List<Hrana> mst = kruskal(ms);
System.out.println(mst);
}
}