Skip to content

Commit

Permalink
Merge pull request #21 from alvredaivena/master
Browse files Browse the repository at this point in the history
added Dijkstra
  • Loading branch information
kokizzu committed Dec 13, 2014
2 parents f54b946 + 63c516c commit e3588a5
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
70 changes: 70 additions & 0 deletions Dijkstra.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import "fmt"
import "sort"

// O(n)
func MinCost(cost []int, dist []int) (int, int) {
minn := 100000000
to := 100000000
for j:=0; j<len(cost); j++ {
if cost[j] != 0 && dist[j] != 1 {
if cost[j] < minn {
minn = cost[j]
to = j
}
}
}
return minn, to
}

// O(n^2)
func Dijkstra(graph [][]int, vertex int) (map[string]int, int) {
min := 0
path := make(map[string]int)
count := 0
next := 0
path_temp := ""
dist := make([]int, vertex)
for len(path) < vertex-1 {
dist[next] = 1
a, b := MinCost(graph[next], dist)
path_temp = string(count+'1')+". "+string(next+'A')+"->"+string(b+'A')
path[path_temp] = a
min += a
next = b
count += 1
}
return path, min
}

func main(){
vertex := 5
/*
2 3
A----B----C
| / \ |
6| 8/ \5 |7
| / \ |
D---------E
9
*/
graph := [][]int{
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
}
path, min := Dijkstra(graph, vertex)
fmt.Println("Shortest path : ")
var keys []string
for k := range path {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, ":", path[k])
}
fmt.Println("Total cost :", min)
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ ChangeLog:
* 2014-12-11 added QuickSort, CombSort, Heapsort (Agung)
* 2014-12-11 added CocktailSort, added Non-recursive MergeSort (Alvreda)
* 2014-12-13 added Shellsort( versi biasa, Ciura, Knuth) (Marcelinus Devin)
* 2014-12-14 added Dijkstra (Alvreda)

TODO:
=====
Expand All @@ -44,4 +45,4 @@ BOUNTY:
* implement Non-recursive Inplace MergeSort +1800, other sorting algorithms, that allow Less/Equal/Swap/Len interface
* implement BinarySearch, JumpSearch, InterpolationSearch +400 that Allow Less/Equal interface
* implement R-Tree +5000, k-d Tree +8000 (using reflection)
* implement any other data structure or algorithm (bounty may vary, contact me for details)
* implement any other data structure or algorithm (bounty may vary, contact me for details)

0 comments on commit e3588a5

Please sign in to comment.