Skip to content

Commit 0597917

Browse files
committed
Added depthFirstSearch.kt
1 parent 8e3b6a2 commit 0597917

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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 = {}) {
7+
8+
init { init() }
9+
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()
15+
}
16+
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+
}
34+
}
35+
}
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()
51+
}
52+
53+
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+
}
65+
}
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+
)
77+
}

0 commit comments

Comments
 (0)