int INF = 99999; int[][] graph = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; int V = 4; int[][] dist = new int[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { dist[i][j] = graph[i][j]; } } for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) { System.out.print("INF "); } else { System.out.print(dist[i][j] + " "); } } System.out.println(); }
The Floyd Warshall algorithm updates the shortest paths by considering each vertex as an intermediate point. The final matrix shows the shortest distances between all pairs. For example, the shortest path from vertex 0 to 3 is 9 (0->1->2->3).
Floyd Warshall uses three nested loops each running V times, resulting in O(V^3) time complexity.
int INF = 99999; int[][] graph = { {0, 3, INF}, {2, 0, INF}, {INF, 7, 0} }; int V = 3; int[][] dist = new int[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { dist[i][j] = graph[i][j]; } } for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } System.out.println(dist[0][2]);
The distance from vertex 0 to 2 remains INF (99999) because no path exists connecting them through intermediate vertices.
int INF = 99999; int[][] graph = { {0, 1, INF}, {INF, 0, -1}, {-1, INF, 0} }; int V = 3; int[][] dist = new int[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { dist[i][j] = graph[i][j]; } } for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } boolean hasNegativeCycle = false; for (int i = 0; i < V; i++) { if (dist[i][i] < 0) { hasNegativeCycle = true; break; } } System.out.println(hasNegativeCycle);
A negative cycle exists if any diagonal element in the distance matrix becomes negative after Floyd Warshall completes. Here, it does.
Floyd Warshall can handle negative edge weights and detect negative cycles, which Dijkstra cannot. This makes Floyd Warshall more suitable for dense graphs with such edges.
