Jack goes to Rapture

  • + 0 comments

    Kotlin solution similar to Dijkstra's algorithm with different distance calculation (weights are not cumulative like in the traditional problem)

    fun jackGoesToRapture(N: Int, edges: Array<Array<Int>>): Int? {
        val nodeList = (1..N).map { Node(it) }
        for (edge in edges) {
            val a = edge[0]
            val b = edge[1]
            val cost = edge[2]
            nodeList[a-1].connections[nodeList[b-1]] = cost
            nodeList[b-1].connections[nodeList[a-1]] = cost
        }
        val queue = PriorityQueue<NodeAndCost>(compareBy { it.cost })
        val distances = mutableMapOf<Node, Int>()
        queue.add(NodeAndCost(nodeList[0], 0))
        distances[nodeList[0]] = 0
        
        while (!queue.isEmpty()) {
            val n0 = queue.remove().node
            val roads = n0.connections
            for (n in roads.keys) {
                val cost = kotlin.math.max(roads[n]!!, distances[n0]!!)
                if (cost < distances[n] ?: Int.MAX_VALUE) {
                    distances[n] = cost
                    queue.add(NodeAndCost(n, cost))
                }
            }
        }
        return distances[nodeList[nodeList.size - 1]]
    }
    
    data class Node(val name: Int) {
        val connections: MutableMap<Node, Int> = mutableMapOf()
    }
    
    data class NodeAndCost(val node: Node, var cost: Int)