import java.util.Arrays;
import java.util.Map;
import sk.upjs.paz.graph.Graph;
import sk.upjs.paz.graph.Vertex;
public class BellmanFord {
static String[] labely;
public static double[][] vytvorMaticuSusednosti(Graph g) {
// Vyrobime pole vrcholov
Vertex[] vrcholy = new Vertex[g.getVertices().size()];
labely = new String[g.getVertices().size()];
int idx = 0;
for (Vertex v: g.getVertices()) {
vrcholy[idx] = v;
labely[idx] = v.getLabel();
idx++;
}
// Vyrobime maticu susednosti;
double[][] matica = new double[vrcholy.length][vrcholy.length];
for (int i=0; i<vrcholy.length; i++)
for (int j=0; j<vrcholy.length; j++)
if (g.hasEdge(vrcholy[i], vrcholy[j])) {
matica[i][j] = g.getEdge(vrcholy[i], vrcholy[j]).getWeight();
} else {
matica[i][j] = Double.POSITIVE_INFINITY;
}
return matica;
}
public static double[] bellmanFord(double[][] maticaSusednosti, String odkial) {
double[] d = new double[maticaSusednosti.length];
for (int i = 0; i < d.length; i++) {
if (labely[i].equals(odkial)) {
d[i] = 0;
} else {
d[i] = Double.POSITIVE_INFINITY;
}
}
for (int i = 0; i < maticaSusednosti.length; i++) {
//zrelaxujeme vsetky hrany
for (int u = 0; u < maticaSusednosti.length; u++) {
for (int v = 0; v < maticaSusednosti.length; v++) {
if (maticaSusednosti[u][v] < Double.POSITIVE_INFINITY) {
relax(u,v,d,maticaSusednosti);
}
}
}
}
return d;
}
public static void relax(int u, int v, double[] d, double[][] maticaSusednosti) {
if (d[v] > d[u] + maticaSusednosti[u][v]) {
d[v] = d[u] + maticaSusednosti[u][v];
}
}
/**
* @param args
*/
public static void main(String[] args) {
// Vytvorime graf
Graph fb = new Graph();
// Nacitame zoznam hran zo suboru
fb.setDirected(true);
fb.loadFromFile("graf.txt");
double[][] matica = vytvorMaticuSusednosti(fb);
System.out.println(Arrays.toString(labely));
for (int i = 0; i < matica.length; i++) {
System.out.println(Arrays.toString(matica[i]));
}
System.out.println(Arrays.toString(bellmanFord(matica, "A")));
}
}