Skip to content

Commit 2b795d5

Browse files
committed
Added depth first search in kotlin
1 parent 0597917 commit 2b795d5

File tree

1 file changed

+18
-65
lines changed

1 file changed

+18
-65
lines changed
Lines changed: 18 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,30 @@
1-
import java.util.*
2-
import kotlin.collections.HashSet
3-
4-
class NodeNotFoundException : Throwable("Node was not found")
5-
6-
class Graph<V>(var value: V, var nodes: MutableSet<Graph<V>> = HashSet(), init: Graph<V>.() -> Unit = {}) {
1+
class Graph(size: Int, init: Graph.() -> Unit) {
2+
val adjacency: Array<MutableList<Int>> = Array(size) { ArrayList() }
73

84
init { init() }
95

10-
fun add(value: V, nodes: MutableSet<Graph<V>> = HashSet(), init: Graph<V>.() -> Unit = {}) {
11-
this.nodes.add(Graph(value, nodes, init))
12-
}
13-
14-
override fun toString() = value.toString()
6+
fun addEdge(node: Int, to: Int) = adjacency[node].add(to)
157
}
168

17-
fun <V> depthFirstSearch(root: Graph<V>, searchValue: V): Result<List<Graph<V>>> {
18-
19-
val map = HashMap<Graph<V>, Graph<V>>()
20-
val toSearch = Stack<Graph<V>>().apply { push(root) }
21-
22-
while (toSearch.isNotEmpty()) {
23-
24-
val currentNode = toSearch.pop()
25-
26-
if (currentNode.value == searchValue)
27-
return Result.success(mapToRoute(root, currentNode, map))
28-
29-
currentNode.nodes.forEach {
30-
if (!map.containsKey(it)) {
31-
map[it] = currentNode
32-
toSearch.push(it)
33-
}
9+
fun depthFirstSearch(graph: Graph, current: Int, searched: Array<Boolean> = Array(graph.adjacency.size) { false }) {
10+
if(!searched[current]) {
11+
searched[current] = true
12+
print("$current ")
13+
for (next in graph.adjacency[current]) {
14+
depthFirstSearch(graph, next, searched)
3415
}
3516
}
36-
return Result.failure(NodeNotFoundException())
37-
}
38-
39-
fun <V> mapToRoute(root: Graph<V>, to: Graph<V>, path: Map<Graph<V>, Graph<V>>): List<Graph<V>> {
40-
41-
var position: Graph<V> = to
42-
val result: MutableList<Graph<V>> = ArrayList()
43-
44-
while (position != root) {
45-
result.add(position)
46-
position = path[position]!!
47-
}
48-
49-
result.add(root)
50-
return result.reversed()
5117
}
5218

5319
fun main() {
54-
55-
val graph = Graph(1) {
56-
add(10) {
57-
add(2) {
58-
add(4)
59-
}
60-
add(4)
61-
}
62-
add(2) {
63-
add(7)
64-
}
20+
val graph = Graph(4) {
21+
addEdge(0, 1)
22+
addEdge(0, 2)
23+
addEdge(1, 2)
24+
addEdge(2, 0)
25+
addEdge(2, 3)
26+
addEdge(3, 3)
6527
}
66-
67-
val result = depthFirstSearch(graph, 4)
68-
69-
result.fold(
70-
onSuccess = {
71-
println(it.joinToString(separator = " -> "))
72-
},
73-
onFailure = {
74-
println("No node with this value was found")
75-
}
76-
)
28+
println("Following is Depth First Traversal " + "(Starting from vertex 2)")
29+
depthFirstSearch(graph, 2)
7730
}

0 commit comments

Comments
 (0)