forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUWGraph.kt
46 lines (35 loc) Β· 1.15 KB
/
UWGraph.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
41
42
43
44
45
46
package algo.graphs.undirected.weighted
import algo.datastructures.Queue
import algo.graphs.Graph
class UWGraph(public override val V: Int): Graph {
public override var E: Int = 0
private val adj: Array<Queue<Edge>> = Array(V) { Queue<Edge>() }
public class Edge(public val v: Int, public val w: Int, public val weight: Double): Comparable<Edge> {
override fun compareTo(other: Edge): Int {
return this.weight.compareTo(other.weight)
}
fun other(s: Int): Int {
if (s == v) return w
if (s == w) return v
throw IllegalArgumentException()
}
}
public fun addEdge(v: Int, w: Int, weight: Double) {
val edge = Edge(v, w, weight)
adj[v].add(edge)
adj[w].add(edge)
E++
}
public fun adjacentEdges(v: Int): Collection<Edge> {
return adj[v]
}
public override fun adjacentVertices(v: Int): Collection<Int> {
return adjacentEdges(v).map { it.other(v) }
}
public fun degree(v: Int): Int {
return adj[v].size
}
public fun edges(): Collection<Edge> {
return adj.flatMap { it }
}
}