📖 Scenario: You are working as a city planner. You have a map of 4 cities connected by roads with different travel times. You want to find the shortest travel time between every pair of cities.
🎯 Goal: Build a program using the Floyd Warshall algorithm to find the shortest travel times between all pairs of cities.
📋 What You'll Learn
Create a 2D slice called dist representing the travel times between cities
Create a variable n for the number of cities
Use three nested for loops with variables k, i, and j to update shortest paths
Print the final dist matrix showing shortest travel times
💡 Why This Matters
🌍 Real World
City planners and GPS systems use shortest path algorithms like Floyd Warshall to find the quickest routes between locations.
💼 Career
Understanding all pairs shortest path algorithms is important for roles in software engineering, data analysis, and network optimization.
Progress0 / 4 steps
1
Create the initial distance matrix
Create a 2D slice called dist with these exact values representing travel times between 4 cities: [[0, 5, 999, 10], [999, 0, 3, 999], [999, 999, 0, 1], [999, 999, 999, 0]]. Use 999 to represent no direct road.
DSA Go
Hint
Use a slice of slices to create the 2D matrix. Use 999 for no direct road.
2
Set the number of cities
Create an integer variable called n and set it to the number of cities in dist.
DSA Go
Hint
Use the len function to get the number of rows in dist.
3
Implement the Floyd Warshall algorithm
Use three nested for loops with variables k, i, and j from 0 to n to update dist[i][j] with the minimum of its current value and dist[i][k] + dist[k][j].
DSA Go
Hint
Use nested loops and update dist[i][j] only if the new path is shorter.
4
Print the shortest path matrix
Use a for loop with variable i from 0 to n to print each row of dist using fmt.Println(dist[i]).
DSA Go
Hint
Use a loop to print each row of the dist matrix.
Practice
(1/5)
1. What is the main purpose of the Floyd Warshall algorithm in graph theory?
easy
A. To perform a depth-first search traversal
B. To find the minimum spanning tree of a graph
C. To detect cycles in a graph
D. To find the shortest paths between all pairs of vertices in a weighted graph
Solution
Step 1: Understand Floyd Warshall's goal
The Floyd Warshall algorithm is designed to find shortest paths between every pair of vertices in a weighted graph, including negative weights but no negative cycles.
Step 2: Compare with other graph algorithms
Minimum spanning tree algorithms find a subset of edges connecting all vertices with minimum total weight, cycle detection finds cycles, and DFS is a traversal method. These are different from Floyd Warshall's all pairs shortest path goal.
Final Answer:
To find the shortest paths between all pairs of vertices in a weighted graph -> Option D
Quick Check:
Floyd Warshall = All pairs shortest paths [OK]
Hint: Floyd Warshall finds shortest paths between all vertex pairs [OK]
Common Mistakes:
Confusing Floyd Warshall with minimum spanning tree algorithms
Thinking it only finds shortest path from one source
Assuming it detects cycles
Mixing it with traversal algorithms like DFS
2. Which of the following is the correct way to initialize the distance matrix dist for Floyd Warshall in Go, given graph as adjacency matrix and V as number of vertices?
easy
A. dist = graph
B. for i := 0; i < V; i++ { dist[i] = graph[i] }
C. for i := 0; i < V; i++ { for j := 0; j < V; j++ { dist[i][j] = graph[i][j] } }
D. dist := make([]int, V*V)
Solution
Step 1: Understand matrix copying in Go
In Go, to copy a 2D slice (matrix), you must copy each element individually. Assigning one slice to another copies the reference, not the data.
Step 2: Analyze options
for i := 0; i < V; i++ { for j := 0; j < V; j++ { dist[i][j] = graph[i][j] } } copies each element explicitly, correctly initializing dist. for i := 0; i < V; i++ { dist[i] = graph[i] } copies slice references, not elements. dist = graph assigns reference, not copy. dist := make([]int, V*V) creates a 1D slice, not a 2D matrix.
Final Answer:
for i := 0; i < V; i++ { for j := 0; j < V; j++ { dist[i][j] = graph[i][j] } } -> Option C
Quick Check:
Copy element-wise for matrix copy [OK]
Hint: Copy 2D slices element-wise to avoid reference issues [OK]
3. What will be the output distance matrix after running Floyd Warshall on the following graph represented as adjacency matrix (9999 means no direct edge):
Hint: Update dist[i][j] using intermediate k for all triples [OK]
Common Mistakes:
Not updating paths through intermediate vertices
Confusing no edge (9999) with zero
Forgetting to update all pairs in nested loops
Incorrectly summing distances
4. Consider this Go code snippet for Floyd Warshall. What is the bug causing incorrect shortest path results?
for k := 0; k < V; k++ {
for i := 0; i < V; i++ {
for j := 0; j < V; j++ {
if dist[i][k] + dist[k][j] < dist[i][j] {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
medium
A. Missing check for dist[i][k] or dist[k][j] being infinity before addition
B. No bug; code is correct
C. Loop order should be i, j, k instead of k, i, j
D. Should use <= instead of < in if condition
Solution
Step 1: Understand the addition of distances
When dist[i][k] or dist[k][j] is infinity (e.g., 9999), adding them can cause integer overflow or incorrect comparisons.
Step 2: Identify missing checks
The code does not check if dist[i][k] or dist[k][j] is infinity before adding. This can cause wrong updates to dist[i][j]. Proper code should skip addition if either is infinity.
Final Answer:
Missing check for dist[i][k] or dist[k][j] being infinity before addition -> Option A
Quick Check:
Check infinity before adding distances [OK]
Hint: Always check for infinity before adding distances [OK]
Common Mistakes:
Ignoring infinity checks causing wrong updates
Changing loop order unnecessarily
Using <= instead of < does not fix logic
Assuming code is correct without boundary checks
5. Given a graph with vertices representing cities and edges representing travel times, how can Floyd Warshall be adapted to also reconstruct the shortest path between any two cities?
hard
A. Store all paths explicitly in a list during the algorithm
B. Maintain a separate predecessor matrix updated during relaxation to track paths
C. Run Dijkstra's algorithm for each city instead
D. Use BFS instead of Floyd Warshall for path reconstruction
Solution
Step 1: Understand Floyd Warshall's limitation
Floyd Warshall computes shortest distances but does not store path details by default.
Step 2: Use predecessor matrix for path reconstruction
By maintaining a predecessor matrix where predecessor[i][j] stores the vertex before j on the shortest path from i, we can reconstruct the path after the algorithm finishes.
Step 3: Other options analysis
Storing all paths explicitly is inefficient. Running Dijkstra repeatedly is possible but less efficient for dense graphs. BFS is not suitable for weighted graphs.
Final Answer:
Maintain a separate predecessor matrix updated during relaxation to track paths -> Option B