Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8fe872c

Browse files
Added Bellman ford algorithm in Go
1 parent d8549ea commit 8fe872c

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

‎Graphs/BellmanFord.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package main
2+
import (
3+
"fmt"
4+
"math"
5+
)
6+
7+
func main(){
8+
9+
var times =[][]int{ {1,2,1},{2,3,1},{3,4,1}}
10+
var N, K,g int
11+
N = 4
12+
K = 1
13+
V :=3
14+
E :=3
15+
/*
16+
var N,K,g,V,E int
17+
fmt.Scanf("%d%d",&V,&E)
18+
//var times[V][E] int
19+
times :=make([][]int,V,E)
20+
for i:=0;i<V;i++ {
21+
var input int;
22+
for j:=0;j<E;j++ {
23+
fmt.Scanf("%d",&input)
24+
times[i][j]=input
25+
}
26+
}
27+
fmt.Scanf("%d%d",&N,&K)
28+
*/
29+
g= BellmanFord(times,N,K,V,E)
30+
fmt.Printf("Steps needed to reach the destination from vertex %d to vertex %d is %d.\n\n",K,N,g)
31+
if detectCycle(times, N) {
32+
fmt.Println("There was a negative cost cycle detected." )
33+
}else{
34+
fmt.Println("There was no cycle detected");
35+
}
36+
}
37+
38+
func detectCycle(a [][]int, N int) bool {
39+
for i := 0; i < len(a); i++ {
40+
//for j:=0; j< len(a[i]);j++){
41+
if a[i][i] < 0 {
42+
return true
43+
}
44+
}
45+
return false
46+
}
47+
48+
func BellmanFord(times [][]int, N int, K int, V int, E int) int {
49+
dist := make([]int, N+1)
50+
for i, _ := range dist {
51+
dist[i] = math.MaxInt32
52+
}
53+
dist[K] = 0
54+
for i := 0; i < V ; i++ {
55+
for j:= 0; j < E; j++ {
56+
if dist[times[j][0]] + times[j][2] < dist[times[j][1]] {
57+
dist[times[j][1]] =dist[times[j][0]] + times[j][2]
58+
}
59+
}
60+
}
61+
fmt.Println("Vertex \t\t Distance from Source")
62+
for i :=1; i<=N; i++ {
63+
fmt.Printf("%d \t\t %d\n",i,dist[i]);
64+
}
65+
fmt.Println()
66+
67+
maxWait := 0
68+
69+
for x := 1; x <= N; x++ {
70+
maxWait = int(math.Max(float64(maxWait), float64(dist[x])))
71+
}
72+
73+
if maxWait != math.MaxInt32 {
74+
return maxWait
75+
} else {
76+
return -1
77+
}
78+
79+
}
80+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /