39 lines
1.5 KiB
Kotlin
39 lines
1.5 KiB
Kotlin
import java.io.File
|
|
|
|
fun findPath(current: String, to: String, connections: Map<String, List<String>>, visited: MutableList<String> = mutableListOf()): Boolean {
|
|
if(current == to) return true
|
|
if(visited.contains(current)) return false
|
|
visited.add(current)
|
|
return connections[current]!!.any { findPath(it, to, connections, visited) }
|
|
}
|
|
|
|
fun findGroup(current: String, connections: Map<String, List<String>>, visited: MutableList<String> = mutableListOf()): MutableList<String> {
|
|
if(visited.contains(current)) return visited
|
|
visited.add(current)
|
|
for(connection in connections[current]!!) findGroup(connection, connections, visited)
|
|
return visited
|
|
}
|
|
|
|
|
|
fun main(args: Array<String>) {
|
|
val sourceFile = File("../puzzle_12.txt")
|
|
// val sourceFile = File("test.txt")
|
|
val connectionMaps = mutableMapOf<String, MutableList<String>>()
|
|
sourceFile.readLines().forEach {
|
|
val programId = it.split(" <-> ")[0]
|
|
val programs = it.split(" <-> ")[1].split(", ")
|
|
programs
|
|
.map { connectionMaps.computeIfAbsent(it) { mutableListOf() } }
|
|
.forEach { it.add(programId) }
|
|
connectionMaps.computeIfAbsent(programId) { mutableListOf() }.addAll(programs)
|
|
}
|
|
val total = connectionMaps.keys.sumBy { if(findPath(it, "0", connectionMaps)) 1 else 0 }
|
|
val programs = connectionMaps.keys
|
|
var groups = 0
|
|
while(programs.size > 0) {
|
|
programs.removeAll(findGroup(programs.first(), connectionMaps))
|
|
groups++
|
|
}
|
|
println(total)
|
|
println(groups)
|
|
} |