File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change @@ -5,8 +5,8 @@ import scala.collection.mutable
5
5
case class Edge [T ](src : T , dest : T , weight : Double )
6
6
7
7
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 ()
10
10
11
11
def addVertex (vertex : T ): Unit = {
12
12
adjacencyList.getOrElseUpdate(vertex, mutable.ListBuffer ())
You can’t perform that action at this time.
0 commit comments