CodexBloom - Programming Q&A Platform

Confusion with Implementing the Floyd-Warshall Algorithm for All-Pairs Shortest Paths in Java

πŸ‘€ Views: 3 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
java algorithms floyd-warshall Java

I'm working through a tutorial and I've encountered a strange issue with I tried several approaches but none seem to work. I'm trying to implement the Floyd-Warshall algorithm in Java to find the shortest paths between all pairs of vertices in a weighted graph. However, I'm encountering issues where the distances between certain nodes are not being updated correctly, leading to incorrect results. Here’s a simplified version of my implementation: ```java public class FloydWarshall { public static void floydWarshall(int[][] graph) { int V = graph.length; int[][] dist = new int[V][V]; // Initialize the distance array for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (i == j) { dist[i][j] = 0; } else if (graph[i][j] != 0) { dist[i][j] = graph[i][j]; } else { dist[i][j] = Integer.MAX_VALUE; } } } // Update distances using Floyd-Warshall algorithm 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] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE) { dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } } printSolution(dist); } public static void printSolution(int[][] dist) { int V = dist.length; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == Integer.MAX_VALUE) { System.out.print("INF " + " "); } else { System.out.print(dist[i][j] + " "); } } System.out.println(); } } } ``` In my test case, I have a graph with vertices 0, 1, and 2, where: - The edge from 0 to 1 has a weight of 5. - The edge from 1 to 2 has a weight of 3. - The edge from 0 to 2 has a weight of 10 (which I expect to be updated to 8). After running my code, the output shows: ``` 0 5 10 INF 0 3 INF INF 0 ``` I was expecting the distance from 0 to 2 to be updated to 8, but it remains as 10. I also tried validating the initialization of my distance array and ensured that the graph matrix is set up correctly. I suspect there might be an issue with how I'm handling the updates, but I'm not sure. Any insights into why this might be happening? Any help would be greatly appreciated! I'm working on a desktop app that needs to handle this. Any examples would be super helpful. I'd really appreciate any guidance on this. I'm coming from a different tech stack and learning Java. Any ideas what could be causing this?