Skip to content

Commit 7def69d

Browse files
implemented Bellmann Ford
1 parent 0d8b76d commit 7def69d

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package algorithms.graph
2+
3+
import datastructures.graph.Graph
4+
import scala.collection.mutable
5+
6+
def bellmanford[T](graph: Graph[T], start: T): (mutable.Map[T, Int], Boolean) = {
7+
val distances = mutable.Map[T, Int]().withDefaultValue(Int.MaxValue)
8+
val pi = mutable.Map[T, T]()
9+
10+
distances(start) = 0
11+
12+
for (vertex <- graph.adjacencyList.keys.toList) {
13+
if vertex != start then distances(vertex) = Int.MaxValue
14+
}
15+
for (i <- 1 until graph.adjacencyList.keys.toList.length) {
16+
for (edge <- graph.edges) {
17+
if (distances(edge.dest) > distances(edge.src) + edge.weight.toInt) {
18+
distances(edge.dest) = distances(edge.src) + edge.weight.toInt
19+
pi(edge.dest) = edge.src
20+
}
21+
}
22+
}
23+
for (edge <- graph.edges) {
24+
if (distances(edge.dest) > distances(edge.src) + edge.weight.toInt) {
25+
return (distances, false)
26+
}
27+
}
28+
29+
(distances, true)
30+
}

src/main/scala/algorithms/graph/Dijkstra.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import scala.collection.mutable
99
/// Uses a priority queue-based approach
1010
/// Runs in O((V + E) log V) time complexity
1111

12-
def dijkstra[T](graph: Graph[T], start: T): Unit = {
12+
def dijkstra[T](graph: Graph[T], start: T): Map[T, Int] = {
1313
val distances = mutable.Map[T, Int]().withDefaultValue(Int.MaxValue)
1414
val visited = mutable.Set[T]()
1515
val priorityQueue = PriorityQueue[(T, Int)]()(Ordering.by(-_._2))

0 commit comments

Comments
 (0)