data class Node(val value: String, val parents: List = emptyList(), var children: List = emptyList()){ override fun toString() = value //avoid stack-overflow override fun hashCode() = value.hashCode() override fun equals(other: Any?) = value == (other as? Node)?.value } fun Node.bfs(): Sequence { val start = generateSequence(this) { it.parents.first() }.last() val queue: Queue = LinkedList().also { it.add(start) } val visited = HashSet() fun Node.hasUnvisitedParent() = (parents - visited).any() return buildSequence { while( ! queue.isEmpty()){ while(queue.any() && (queue.peek() in visited || queue.peek().hasUnvisitedParent())){ queue.remove() } if(queue.isEmpty()){ return@buildSequence } val next = queue.remove() yield(next) visited += next queue += next.children } } }