Skip to content

Commit 4e8728e

Browse files
added topoSort
1 parent b6f04da commit 4e8728e

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package algorithms.graph
2+
3+
import datastructures.graph._
4+
import scala.collection.mutable
5+
6+
//Kahns Algorithm
7+
def topologicalSort[T](graph : Graph[T]) : Option[List[T]] = {
8+
9+
val inDegree = mutable.Map[T, Int]().withDefaultValue(0)
10+
11+
for ((src, neighbors) <- graph.adjacencyList) {
12+
for ((dest, _) <- neighbors) {
13+
inDegree.update(dest, inDegree(dest) + 1)
14+
}
15+
}
16+
17+
// Initialize queue with nodes having in-degree 0
18+
val queue = mutable.Queue[T]()
19+
for (vertex <- graph.adjacencyList.keys if inDegree(vertex) == 0) {
20+
queue.enqueue(vertex)
21+
}
22+
23+
val sortedList = mutable.ListBuffer[T]()
24+
25+
// Process queue
26+
while (queue.nonEmpty) {
27+
val vertex = queue.dequeue()
28+
sortedList.append(vertex)
29+
30+
for ((neighbor, _) <- graph.adjacencyList(vertex)) {
31+
inDegree.update(neighbor, inDegree(neighbor) - 1)
32+
if (inDegree(neighbor) == 0) {
33+
queue.enqueue(neighbor)
34+
}
35+
}
36+
}
37+
38+
// Cycle check
39+
if (sortedList.size == graph.adjacencyList.size) Some(sortedList.toList) else None
40+
}
41+
42+

src/main/scala/datastructures/graph/graph.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import scala.collection.mutable
55
case class Edge[T](src: T, dest: T, weight: Double)
66

77
class Graph[T](val isDirected: Boolean) {
8-
private val adjacencyList: mutable.Map[T, mutable.ListBuffer[(T, Double)]] = mutable.Map()
9-
private val edges: mutable.ListBuffer[Edge[T]] = mutable.ListBuffer()
8+
val adjacencyList: mutable.Map[T, mutable.ListBuffer[(T, Double)]] = mutable.Map()
9+
val edges: mutable.ListBuffer[Edge[T]] = mutable.ListBuffer()
1010

1111
def addVertex(vertex: T): Unit = {
1212
adjacencyList.getOrElseUpdate(vertex, mutable.ListBuffer())

0 commit comments

Comments
 (0)