Floyd Warshall algorithm

Floyd-Warshall efficiently finds the shortest paths between all pairs of vertices in a graph. Handles graphs with negative edge weights, but it cannot detect negative cycles.

Hint

Initialization:

Floyd-Warshall Algorithm:

Result:

# Python implementation
def floydWarshall(graph):
  V = len(graph)
  dist = [[float('inf') for _ in range(V)] for _ in range(V)]
  
  for i in range(0, V):
    for j in range(0, V):
      dist[i][j] = float('inf') if graph[i][j] == float('inf') else graph[i][j]

  for k in range(0, V):
    for i in range(0, V):
      for j in range(0, V):
        if dist[i][k] != float('inf') and dist[k][j] != float('inf') and dist[i][j] > dist[i][k] + dist[k][j]:
          dist[i][j] = dist[i][k] + dist[k][j]

  return dist

graph = [
  [0, 5, float('inf'), 10],
  [float('inf'), 0, 3, float('inf')],
  [float('inf'), float('inf'), 0, 1],
  [float('inf'), float('inf'), float('inf'), 0]
]

print(floydWarshall(graph))
// Javascript implementation
function floydWarshall(graph) {
  const V = graph.length;
  const dist = [];
  
  for (let i = 0; i < V; i++) {
    dist[i] = [];
    for (let j = 0; j < V; j++) {
      dist[i][j] = graph[i][j] === Infinity ? Infinity : graph[i][j]; 
    }
  }

  for (let k = 0; k < V; k++) {
    for (let i = 0; i < V; i++) {
      for (let j = 0; j < V; j++) {
        if (dist[i][k] !== Infinity && dist[k][j] !== Infinity && dist[i][j] > dist[i][k] + dist[k][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
        }
      }
    }
  }

  return dist;
}

const graph = [
  [0, 5, Infinity, 10],
  [Infinity, 0, 3, Infinity],
  [Infinity, Infinity, 0, 1],
  [Infinity, Infinity, Infinity, 0]
];

console.log(floydWarshall(graph));