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 () }
7
3
8
4
init { init () }
9
5
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)
15
7
}
16
8
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)
34
15
}
35
16
}
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
17
}
52
18
53
19
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 )
65
27
}
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 )
77
30
}
0 commit comments