All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1501_1600.s1600_throne_inheritance.ThroneInheritance.kt Maven / Gradle / Ivy

There is a newer version: 1.32
Show newest version
package g1501_1600.s1600_throne_inheritance

// #Medium #Hash_Table #Depth_First_Search #Tree #Design
// #2023_06_14_Time_1847_ms_(100.00%)_Space_136.1_MB_(100.00%)

class ThroneInheritance(private val king: String) {
    private val graph: HashMap>
    private val isDead: HashSet

    init {
        graph = HashMap()
        isDead = HashSet()
        graph[king] = LinkedHashSet()
    }

    fun birth(parentName: String, childName: String) {
        graph.putIfAbsent(parentName, LinkedHashSet())
        graph[parentName]!!.add(childName)
    }

    fun death(name: String) {
        isDead.add(name)
    }

    fun getInheritanceOrder(): List {
        val inheritance: MutableList = ArrayList()
        val visited = HashSet()
        dfs(graph, king, inheritance, visited)
        return inheritance
    }

    fun dfs(
        graph: Map>,
        src: String,
        l: MutableList,
        visited: MutableSet
    ) {
        visited.add(src)
        if (!isDead.contains(src)) {
            l.add(src)
        }
        if (!graph.containsKey(src)) {
            return
        }
        for (s in graph[src]!!) {
            if (!visited.contains(s)) {
                dfs(graph, s, l, visited)
            }
        }
    }
}
/*
 * Your ThroneInheritance object will be instantiated and called as such:
 * var obj = ThroneInheritance(kingName)
 * obj.birth(parentName,childName)
 * obj.death(name)
 * var param_3 = obj.getInheritanceOrder()
 */




© 2015 - 2025 Weber Informatics LLC | Privacy Policy