From 1f17712ce4b12e3d2a1b0002f662104ebe196a7e Mon Sep 17 00:00:00 2001 From: ridwanfathin Date: Mon, 12 Oct 2020 09:05:24 +0700 Subject: [PATCH 1/2] add flowd-warshall algorithm --- graph/shortest_distance_fw.go | 57 +++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 graph/shortest_distance_fw.go diff --git a/graph/shortest_distance_fw.go b/graph/shortest_distance_fw.go new file mode 100644 index 0000000..6bcec67 --- /dev/null +++ b/graph/shortest_distance_fw.go @@ -0,0 +1,57 @@ +// shorted distances between every pair of vertices using floyd-warshall algorithm +// https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm +// http://www.golangprograms.com/golang-program-for-implementation-of-floyd-warshall-algorithm.html +package graph + +import ( + "fmt" + "math" +) + +type graph struct { + to int + wt float64 +} + +func floydWarshall(g [][]graph) [][]float64 { + dist := make([][]float64, len(g)) + for i := range dist { + di := make([]float64, len(g)) + for j := range di { + di[j] = math.Inf(1) + } + di[i] = 0 + dist[i] = di + } + for u, graphs := range g { + for _, v := range graphs { + dist[u][v.to] = v.wt + } + } + for k, dk := range dist { + for _, di := range dist { + for j, dij := range di { + if d := di[k] + dk[j]; dij > d { + di[j] = d + } + } + } + } + return dist +} + +func main() { + gra := [][]graph{ + 1: {{2, 3}, {3, 8}, {5, -4}}, + 2: {{4, 1}, {5, 7}}, + 3: {{2, 4}}, + 4: {{1, 2}, {3, -5}}, + 5: {{4, 6}}, + } + + dist := floydWarshall(gra) + //dist[][] will be the output matrix that will have the shortest distances between every pair of vertices + for _, d := range dist { + fmt.Printf("%4g\n", d) + } +} From 13b2e9dab7f1c78d4006a7b4010bed47731528c5 Mon Sep 17 00:00:00 2001 From: ridwanfathin Date: Mon, 12 Oct 2020 09:06:33 +0700 Subject: [PATCH 2/2] fix comment typo --- graph/shortest_distance_fw.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graph/shortest_distance_fw.go b/graph/shortest_distance_fw.go index 6bcec67..f66cd12 100644 --- a/graph/shortest_distance_fw.go +++ b/graph/shortest_distance_fw.go @@ -1,4 +1,4 @@ -// shorted distances between every pair of vertices using floyd-warshall algorithm +// shortest distances between every pair of vertices using floyd-warshall algorithm // https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm // http://www.golangprograms.com/golang-program-for-implementation-of-floyd-warshall-algorithm.html package graph