Ali Hamdi Ali Fadel
· @AliOsm
·
about 3 years
Any ideas on how to improve to implementation?
Ali Hamdi Ali Fadel · @AliOsm · about 3 years
Floyd-Warshall (all pairs shortest path) algorithm implementation.
def floyd_warshall(graph_weights_matrix)n = graph_weights_matrix.sizegraph_weights_matrix.each do |row|raise ArgumentError.new 'The given matrix should be a square matrix' if row.size != nendn.times do |k|n.times do |i|n.times do |j|if graph_weights_matrix[i][j] < graph_weights_matrix[i][k] + graph_weights_matrix[k][j]graph_weights_matrix[i][j] = graph_weights_matrix[i][j]elsegraph_weights_matrix[i][j] = graph_weights_matrix[i][k] + graph_weights_matrix[k][j]endendendendgraph_weights_matrixend
Any ideas on how to improve to implementation?
I checked out the implementation written on wikipedia, and I see your implementation is using K as the innermost loop, I think that alter the algorithm behavior. https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
Thanks for mentioning the issue in the loop variables! I didn’t recognize it while writing. The great thing that it worked for the example I tried :3 I liked point number 4 :)