forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDFS.kt
63 lines (57 loc) Β· 2.08 KB
/
DFS.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package algo.graphs
import algo.datastructures.Stack
class DFS {
companion object Implementations {
fun iterative(graph: Graph,
preorder: ((Int) -> Unit)? = null,
postorder: ((Int) -> Unit)? = null) {
val visited = IntArray(graph.V)
val queue = Stack<Int>()
for (i in 0 until graph.V) {
if (visited[i] == 0) {
queue.push(i)
visited[i] = 1
while (!queue.isEmpty()) {
val v = queue.poll()
if (visited[v] == 1) {
visited[i] = 2
preorder?.invoke(i)
queue.push(v)
for (w in graph.adjacentVertices(v)) {
if (visited[w] == 0) {
queue.push(w)
visited[w] = 1
}
}
} else {
visited[i] = 3
postorder?.invoke(i)
}
}
}
}
}
fun recursive(graph: Graph,
preorder: ((Int) -> Unit)? = null,
postorder: ((Int) -> Unit)? = null) {
val visited = BooleanArray(graph.V)
for (i in 0..graph.V - 1) {
if (!visited[i]) {
dfs(i, graph, visited, preorder, postorder)
}
}
}
private fun dfs(v: Int, graph: Graph, visited: BooleanArray,
preorder: ((Int) -> Unit)? = null,
postorder: ((Int) -> Unit)? = null) {
visited[v] = true
preorder?.invoke(v)
for (w in graph.adjacentVertices(v)) {
if (!visited[w]) {
dfs(w, graph, visited, preorder, postorder)
}
}
postorder?.invoke(v)
}
}
}