Skip to content

Commit 618d601

Browse files
authored
Merge pull request deutranium#218 from InLieuOfLuna/master
Added depth first search in kotlin
2 parents ed1c1a9 + 7f288a2 commit 618d601

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Creates a Graph with [size] nodes
3+
* @param init constructor for adding the edges of the nodes delegated to the instances
4+
*/
5+
class Graph(size: Int, init: Graph.() -> Unit) {
6+
val adjacency: Array<MutableList<Int>> = Array(size) { ArrayList() }
7+
8+
init { init() }
9+
10+
fun addEdge(node: Int, to: Int) = adjacency[node].add(to)
11+
}
12+
13+
/**
14+
* Prints the route taken when exploring the [graph] starting from [current]
15+
* @param searched an array of booleans relating to whether the relating nodes have been searched
16+
*/
17+
fun depthFirstSearch(graph: Graph, current: Int, searched: Array<Boolean> = Array(graph.adjacency.size) { false }) {
18+
if(!searched[current]) {
19+
searched[current] = true
20+
print("$current ")
21+
for (next in graph.adjacency[current]) {
22+
depthFirstSearch(graph, next, searched)
23+
}
24+
}
25+
}
26+
27+
fun main() {
28+
val graph = Graph(4) {
29+
addEdge(0, 1)
30+
addEdge(0, 2)
31+
addEdge(1, 2)
32+
addEdge(2, 0)
33+
addEdge(2, 3)
34+
addEdge(3, 3)
35+
}
36+
println("Following is Depth First Traversal " + "(Starting from vertex 2)")
37+
depthFirstSearch(graph, 2)
38+
}

0 commit comments

Comments
 (0)