diff --git a/06_breadth-first_search/kotlin/BreadthFirstSearch.kt b/06_breadth-first_search/kotlin/BreadthFirstSearch.kt new file mode 100644 index 0000000..be7ea6f --- /dev/null +++ b/06_breadth-first_search/kotlin/BreadthFirstSearch.kt @@ -0,0 +1,50 @@ +typealias Graph = MutableMap> + +fun Graph.breadthFirstSearch(key: V, isSearched: (V) -> Boolean): Boolean { + val queue: Deque = LinkedList() + this[key]?.let { queue += it } + val searched = HashSet() + while (queue.isNotEmpty()) { + val value = queue.pop() + if (!searched.contains(value)) + if (isSearched(value)) { + println("value $value is here!") + return true + } else { + this[value]?.let { queue += it } + searched.add(value) + } + } + return false +} + +data class Person( + val name: String, + val isSellerMango: Boolean = false +) { + override fun equals(other: Any?): Boolean = + if (other is Person) other.name == name + else false + + + override fun hashCode(): Int { + return name.length + } +} + +fun main(args: Array) { + + val graph: Graph = HashMap() + + (graph as java.util.HashMap>).apply { + put(Person("John"), listOf(Person("Sergey"), Person("Viktoria"))) + put(Person("Viktoria"), listOf(Person("Sergey"), Person("Phara"))) + put(Person("Phara"), listOf(Person("Sergey"), Person("Thrall"), Person("Xul"), Person("Juncart", true))) + } + + println( + graph.breadthFirstSearch(Person("John"), Person::isSellerMango) + ) + + +} \ No newline at end of file