-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathDepthFirstSearch.kt
65 lines (51 loc) · 1.86 KB
/
DepthFirstSearch.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
64
65
fun main(args: Array<String>) {
val adjacencyList = AdjacencyList<String>()
val s = adjacencyList.createVertex("S")
val a = adjacencyList.createVertex("A")
val b = adjacencyList.createVertex("B")
val c = adjacencyList.createVertex("C")
val d = adjacencyList.createVertex("D")
val f = adjacencyList.createVertex("F")
val g = adjacencyList.createVertex("G")
val e = adjacencyList.createVertex("E")
adjacencyList.add(Undirected(), s, a)
adjacencyList.add(Undirected(), a, b)
adjacencyList.add(Undirected(), a, d)
adjacencyList.add(Undirected(), a, c)
adjacencyList.add(Undirected(), b, d)
adjacencyList.add(Undirected(), d, g)
adjacencyList.add(Undirected(), d, f)
adjacencyList.add(Undirected(), f, e)
print(adjacencyList)
print(depthFirstSearch(s, e, adjacencyList))
}
fun depthFirstSearch(start: VertexString, end: VertexString, graph: AdjacencyList<String>): Stack<VertexString> {
val visited: MutableSet<VertexString> = mutableSetOf()
val stack = Stack<VertexString>()
stack.push(start)
visited.add(start)
var vertex = stack.peek()
loop@while (vertex != null && vertex != end) {
val neighbors = graph.edges(vertex)
if (neighbors != null && neighbors.count() > 0) {
for (edge in neighbors) {
if (!visited.contains(edge.destination)) {
visited.add(edge.destination)
stack.push(edge.destination)
print("$stack")
vertex = stack.peek()
continue@loop
}
}
} else {
print("backtrack from $vertex")
stack.pop()
vertex = stack.peek()
continue
}
print("backtrack from $vertex")
stack.pop()
vertex = stack.peek()
}
return stack
}