forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 17
/
BFS.kt
31 lines (27 loc) Β· 936 Bytes
/
BFS.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
package algo.graphs
import algo.datastructures.Queue
class BFS {
companion object Implementations {
fun iterative(graph: Graph, levelOrder: ((Int) -> Unit)? = null) {
val visited = BooleanArray(graph.V)
val queue = Queue<Int>()
for (i in 0 until graph.V) {
if (!visited[i]) {
queue.add(i)
visited[i] = true
levelOrder?.invoke(i)
while (!queue.isEmpty()) {
val v = queue.poll()
for (w in graph.adjacentVertices(v)) {
if (!visited[w]) {
queue.add(w)
visited[w] = true
levelOrder?.invoke(i)
}
}
}
}
}
}
}
}