forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DWGraph.kt
40 lines (30 loc) Β· 1.03 KB
/
DWGraph.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package algo.graphs.directed.weighted
import algo.datastructures.Queue
import algo.datastructures.Stack
import algo.graphs.Graph
class DWGraph(public override val V: Int): Graph {
public override var E: Int = 0
private val adj: Array<Queue<Edge>> = Array(V) { Queue<Edge>() }
private val indegree: IntArray = IntArray(V)
public class Edge(public val from: Int, public val to: Int, public val weight: Double)
public fun addEdge(from: Int, to: Int, weight: Double) {
val edge = Edge(from, to, weight)
adj[from].add(edge)
indegree[to]++
E++
}
public fun edges(): Collection<Edge> {
val stack = Stack<Edge>()
adj.flatMap { it }.forEach { stack.push(it) }
return stack
}
public fun adjacentEdges(from: Int): Collection<Edge> {
return adj[from]
}
public override fun adjacentVertices(from: Int): Collection<Int> {
return adjacentEdges(from).map { it.to }
}
public fun outdegree(v: Int): Int {
return adj[v].size
}
}