This repository was archived by the owner on Aug 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 740
/
Copy pathGraphUsingList.kt
85 lines (73 loc) · 2.38 KB
/
GraphUsingList.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import kotlin.collections.ArrayList
class Node<T>(val value: T) {
val neighbors = ArrayList<Node<T>>()
fun addNeighbor(node: Node<T>) = neighbors.add(node)
override fun toString(): String = value.toString()
}
class Graph<T> {
private val nodes = HashSet<Node<T>>()
fun addNode(value: T) {
val newNode = Node(value)
nodes.add(newNode)
}
fun getNode(reference: T): Node<T>? {
return nodes.firstOrNull { it.value == reference }
}
fun addVertex(from: T, to: T) {
getNode(to)?.let { getNode(from)?.addNeighbor(it) }
}
}
fun <T> Graph<T>.bfs(reference: T): List<T> {
getNode(reference)?.let { referenceNode ->
val visited = ArrayList<Node<T>>()
val queue = ArrayList<Node<T>>()
queue.add(referenceNode)
while (queue.isNotEmpty()) {
val node = queue.removeAt(0)
if (!visited.contains(node)) {
visited.add(node)
node.neighbors
.filter { !visited.contains(it) }
.forEach { queue.add(it) }
}
}
return visited.map { it.value }
}
return emptyList()
}
fun <T> Graph<T>.dfs(reference: T): List<T> {
getNode(reference)?.let { referenceNode ->
val visited = ArrayList<Node<T>>()
val stack = ArrayList<Node<T>>()
stack.add(referenceNode)
while (stack.isNotEmpty()) {
val node = stack.removeAt(stack.lastIndex)
if (!visited.contains(node)) {
visited.add(node)
node.neighbors
.filter { !visited.contains(it) }
.forEach { stack.add(it) }
}
}
return visited.map { it.value }
}
return emptyList()
}
fun main() {
val namesGraph = Graph<String>()
namesGraph.addNode("Minato")
namesGraph.addNode("Obito")
namesGraph.addVertex("Minato", "Obito")
namesGraph.addNode("Kakashi")
namesGraph.addVertex("Minato", "Kakashi")
namesGraph.addNode("Rin")
namesGraph.addVertex("Minato", "Rin")
namesGraph.addNode("Naruto")
namesGraph.addVertex("Kakashi", "Naruto")
namesGraph.addNode("Sakura")
namesGraph.addVertex("Kakashi", "Sakura")
namesGraph.addNode("Sasuke")
namesGraph.addVertex("Kakashi", "Sasuke")
print(namesGraph.bfs("Minato"))
print(namesGraph.dfs("Minato"))
}