-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathBreadthFirstTraversal.kt
More file actions
40 lines (34 loc) · 1.02 KB
/
BreadthFirstTraversal.kt
File metadata and controls
40 lines (34 loc) · 1.02 KB
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 algorithmdesignmanualbook.graph
import algorithmdesignmanualbook.withPrint
import java.util.*
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private fun breadthFirstTraversal(graph: Graph) {
val start = graph.getRandomVertex()
val queue = LinkedList<Graph.Vertex>()
queue.addLast(start)
while (queue.isNotEmpty()) {
val first = queue.removeFirst()
if (first.state == Graph.State.PROCESSED) {
continue
}
first.edges.forEach {
if (it.endVertex.state == Graph.State.UNDISCOVERED) {
queue.addLast(it.endVertex)
it.endVertex.state = Graph.State.DISCOVERED
}
}
println(first.value)
first.state = Graph.State.PROCESSED
}
}
fun main() {
withPrint("Graph 1") {
val graph1 = Graph.getDefaultDirected()
breadthFirstTraversal(graph1)
}
withPrint("Graph 2") {
val graph2 = Graph.getDefaultUnDirected()
breadthFirstTraversal(graph2)
}
}