import java.util.*;
public class Floyd {
private static final int INF = Integer.MAX_VALUE;
public static void main(String[] args) {
List<Edge> edges = new ArrayList<>();
edges.add(new Edge(0, 1, 2));
edges.add(new Edge(0, 3, 8));
edges.add(new Edge(1, 2, 3));
edges.add(new Edge(1, 3, 5));
edges.add(new Edge(2, 3, 3));
edges.add(new Edge(3, 4, 3));
edges.add(new Edge(4, 5, 1));
search(edges, 6, 0, 5);
System.out.println("------------------------------------------------------");
search(edges, 7, 0, 6);
System.out.println("\n####################################################");
System.out.println("Graph contains negative weight cycle");
System.out.println("####################################################\n");
edges.clear();
edges.add(new Edge(0, 1, 2));
edges.add(new Edge(0, 3, 8));
edges.add(new Edge(1, 2, 3));
edges.add(new Edge(3, 1, -7));
edges.add(new Edge(2, 3, 3));
edges.add(new Edge(3, 4, 3));
edges.add(new Edge(4, 5, 1));
search(edges, 6, 0, 5);
System.out.println("------------------------------------------------------");
search(edges, 7, 0, 6);
}
public static int search(List<Edge> edges, int n, int start, int end) {
Map<Integer, String> detailedPath = new HashMap<>();
detailedPath.put(start, start + "");
int[][] weights = new int[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(weights[i], INF);
weights[i][i] = 0;
}
for (Edge edge : edges) {
weights[edge.start][edge.end] = edge.weight;
if (edge.start == start) {
detailedPath.put(edge.end, start + "-->" + edge.end);
}
}
for (int interVertex = 0; interVertex < n; interVertex++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == interVertex || interVertex == j) {
continue;
}
int tmp = INF;
if (weights[i][interVertex] != INF && weights[interVertex][j] != INF) {
tmp = weights[i][interVertex] + weights[interVertex][j];
}
if (weights[i][j] > tmp) {
if (i == start) {
detailedPath.put(j, detailedPath.get(interVertex) + "-->" + j);
}
weights[i][j] = tmp;
}
}
}
}
boolean containsNegativeWeightCycle = false;
for (int i = 0; i < n; i++) {
if (weights[i][i] < 0) {
containsNegativeWeightCycle = true;
break;
}
}
if (containsNegativeWeightCycle) {
try {
throw new Exception("Graph contains negative weight cycle");
} catch (Exception e) {
e.printStackTrace();
}
} else if (weights[start][end] != INF) {
System.out.println("From " + start + " to " + end + ", the lowest weight path " + detailedPath.get(end) + ", total weight is " + weights[start][end]);
} else {
System.out.println("From " + start + " to " + end + ", no path exists");
}
return weights[start][end];
}
static class Edge {
int start = 0;
int end = 0;
int weight = 0;
public Edge(int start, int end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
}
}