
Problem
Solution
Submissions
Floyd-Warshall Algorithm
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to implement the Floyd-Warshall algorithm to find the shortest paths between all pairs of vertices in a weighted graph.
Example 1
- Input: graph = {{0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0}}
- Output: 0 5 8 9 INF 0 3 4 INF INF 0 1 INF INF INF 0
- Explanation:
- Step 1: Initialize the distance matrix with the given graph.
- Step 2: For each vertex k as an intermediate vertex, update the shortest path between every pair of vertices (i,j) if path i→k→j is shorter than the direct path i→j.
- Step 3: After processing all vertices as intermediates, the matrix represents the shortest path distances between all pairs of vertices.
- Step 4: Return the final distance matrix.
Example 2
- Input: graph = {{0, 3, INF, 7}, {8, 0, 2, INF}, {5, INF, 0, 1}, {2, INF, INF, 0}}
- Output: 0 3 5 6 5 0 2 3 3 6 0 1 2 5 7 0
- Explanation:
- Step 1: Initialize the distance matrix with the given graph.
- Step 2: For vertex 0 as intermediate, update distances if path i→0→j is shorter.
- Step 3: For vertex 1 as intermediate, update distances if path i→1→j is shorter.
- Step 4: Continue for vertices 2 and 3 as intermediates.
- Step 5: After processing all vertices as intermediates, the matrix represents the shortest path distances between all pairs of vertices.
- Step 6: Return the final distance matrix.
Constraints
- 1 ≤ number of vertices ≤ 100
- Time Complexity: O(n^3), where n is the number of vertices
- Space Complexity: O(n^2)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the Floyd-Warshall algorithm to find the shortest paths between all pairs of vertices.
- Create a distance matrix to store the shortest distances between every pair of vertices.
- Update the distance matrix by considering each vertex as an intermediate vertex.
- The final distance matrix will contain the shortest paths.