gumgum's Garden🌼

Floyd Algorithms

The recurrence isΒ  𝑑𝑖𝑠𝑑(𝑖,𝑗,π‘˜)=π‘šπ‘–π‘›(𝑑𝑖𝑠𝑑(𝑖,𝑗,π‘˜βˆ’1), 𝑑𝑖𝑠𝑑(𝑖,π‘˜,π‘˜βˆ’1)+𝑑𝑖𝑠𝑑(π‘˜,𝑗,π‘˜βˆ’1))𝑑𝑖𝑠𝑑(𝑖,𝑗,π‘˜)=π‘šπ‘–π‘›(𝑑𝑖𝑠𝑑(𝑖,𝑗,π‘˜βˆ’1), 𝑑𝑖𝑠𝑑(𝑖,π‘˜,π‘˜βˆ’1)+𝑑𝑖𝑠𝑑(π‘˜,𝑗,π‘˜βˆ’1)) with the base case 𝑑𝑖𝑠𝑑(𝑖,𝑗,0)=𝑀(𝑖,𝑗). There is only one way we can achieve this iteratively, by calculating all cases ofΒ π‘˜βˆ’1Β before calculating cases ofΒ π‘˜.

def floydWarshall(self, n: int, edges: List[List[int]], distanceThreshold: int):
    dist = [[math.inf for i in range(n)] for j in range(n)]
    for i in range(n):
        dist[i][i] = 0
    for u, v, w in edges:
        dist[u][v] = dist[v][u] = w
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])