0
0
DSA Typescriptprogramming

Floyd Warshall All Pairs Shortest Path in DSA Typescript

Choose your learning style9 modes available
Mental Model
Find the shortest paths between every pair of points by checking if going through a middle point is better than going directly.
Analogy: Imagine you want to find the quickest way to travel between every pair of cities. Sometimes going through a third city is faster than going straight. You check all possible middle cities to find the best routes.
Graph with 4 nodes:
  (0)---5---(1)
   | \       |
   10  3     1
   |     \   |
  (3)---2---(2)

Distance matrix before:
[0, 5, 3, 10]
[∞, 0, 1, ∞]
[∞, ∞, 0, 2]
[∞, ∞, ∞, 0]
Dry Run Walkthrough
Input: Graph with 4 nodes and edges: 0->1=5, 0->3=10, 0->2=3, 1->2=1, 2->3=2; find shortest paths between all pairs
Goal: Calculate shortest distances between every pair of nodes using Floyd Warshall algorithm
Step 1: Initialize distance matrix with direct edges and 0 for self loops
[[0, 5, 3, 10],
 [∞, 0, 1, ∞],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Why: Start with known direct distances and zero for same node
Step 2: Use node 0 as intermediate to update distances
[[0, 5, 3, 10],
 [∞, 0, 1, ∞],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Why: No shorter paths found through node 0 yet
Step 3: Use node 1 as intermediate to update distances
[[0, 5, 3, 10],
 [∞, 0, 1, ∞],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Why: 0->1->2: 5 + 1 = 6 > 3 (direct), so no update. No shorter paths found through node 1.
Step 4: Use node 2 as intermediate to update distances
[[0, 5, 3, 5],
 [∞, 0, 1, 3],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Why: 0->2->3 is shorter (3 + 2 = 5) than 0->3 direct (10), update 0->3 to 5; 1->2->3 is shorter (1 + 2 = 3) than ∞, update 1->3 to 3
Step 5: Use node 3 as intermediate to update distances
[[0, 5, 3, 5],
 [∞, 0, 1, 3],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Why: No shorter paths found through node 3
Result:
[[0, 5, 3, 5],
 [∞, 0, 1, 3],
 [∞, ∞, 0, 2],
 [∞, ∞, ∞, 0]]
Annotated Code
DSA Typescript
class FloydWarshall {
  static INF = Number.MAX_SAFE_INTEGER;

  static floydWarshall(graph: number[][]): number[][] {
    const n = graph.length;
    const dist = Array.from({ length: n }, (_, i) =>
      Array.from({ length: n }, (_, j) => graph[i][j])
    );

    for (let k = 0; k < n; k++) {
      for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
          if (dist[i][k] !== FloydWarshall.INF && dist[k][j] !== FloydWarshall.INF) {
            if (dist[i][k] + dist[k][j] < dist[i][j]) {
              dist[i][j] = dist[i][k] + dist[k][j];
            }
          }
        }
      }
    }
    return dist;
  }
}

// Driver code
const INF = FloydWarshall.INF;
const graph = [
  [0, 5, 3, 10],
  [INF, 0, 1, INF],
  [INF, INF, 0, 2],
  [INF, INF, INF, 0],
];

const result = FloydWarshall.floydWarshall(graph);
for (const row of result) {
  console.log(row.map(x => (x === INF ? '∞' : x)).join(' '));
}
for (let k = 0; k < n; k++) {
Use each node as intermediate to check for shorter paths
if (dist[i][k] !== FloydWarshall.INF && dist[k][j] !== FloydWarshall.INF) {
Check if path through k is possible
if (dist[i][k] + dist[k][j] < dist[i][j]) {
Update distance if going through k is shorter
dist[i][j] = dist[i][k] + dist[k][j];
Set new shorter distance
OutputSuccess
0 5 3 5 ∞ 0 1 3 ∞ ∞ 0 2 ∞ ∞ ∞ 0
Complexity Analysis
Time: O(n^3) because we check all pairs (i, j) for every intermediate node k
Space: O(n^2) because we store distances between all pairs in a matrix
vs Alternative: Compared to running Dijkstra from each node (O(n * (E + V log V))), Floyd Warshall is simpler but slower for sparse graphs
Edge Cases
Graph with no edges except self loops
Distances remain zero on diagonal and infinity elsewhere
DSA Typescript
if (dist[i][k] !== FloydWarshall.INF && dist[k][j] !== FloydWarshall.INF) {
Graph with negative edge weights but no negative cycles
Algorithm correctly finds shortest paths including negative edges
DSA Typescript
if (dist[i][k] + dist[k][j] < dist[i][j]) {
Graph with negative cycle
Algorithm does not detect negative cycles; distances may become incorrect or negative infinity
DSA Typescript
No explicit guard; Floyd Warshall does not handle negative cycle detection here
When to Use This Pattern
When you need shortest paths between all pairs of points and the graph may have negative edges but no negative cycles, use Floyd Warshall to systematically check all intermediate nodes.
Common Mistakes
Mistake: Not checking if intermediate paths exist before adding distances, causing overflow or wrong results
Fix: Add condition to check dist[i][k] and dist[k][j] are not infinity before summing
Mistake: Updating distances without comparing if new path is shorter
Fix: Only update if dist[i][k] + dist[k][j] < dist[i][j]
Summary
Finds shortest paths between all pairs of nodes by considering each node as an intermediate step.
Use when you need all pairs shortest paths and the graph may have negative edges but no negative cycles.
The key insight is that any shortest path can be built by combining shorter paths through intermediate nodes.