Skip to content

Instantly share code, notes, and snippets.

@saldisobi
Created April 9, 2023 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saldisobi/be4e1c20298af3db597b44bab763fa8b to your computer and use it in GitHub Desktop.
Save saldisobi/be4e1c20298af3db597b44bab763fa8b to your computer and use it in GitHub Desktop.
class Solution {
fun networkDelayTime(times: Array<IntArray>, n: Int, k: Int): Int {
val graph = HashMap<Int, LinkedList<IntArray>>()
// step 1 iterate over given times list & create an adjancy list graph representation
times.forEach{node->
val src: Int = node[0]
val target : Int = node[1]
val weight : Int = node[2]
if(!graph.containsKey(src)){
graph[src] = LinkedList<IntArray>()
}
graph[src]?.add(intArrayOf(target, weight))
}
val minHeapOfWeight = PriorityQueue<IntArray>{a,b->
a[1] - b[1] // sort with weights but remains a minHeap
}
val visited = HashSet<Int>()
minHeapOfWeight.add(intArrayOf(k,0))
// Perform Dijkastra
var result: Int = 0 //distance form source node to current node
while(!minHeapOfWeight.isEmpty()){
val popNode = minHeapOfWeight.poll()
val src: Int = popNode[0]
if(visited.contains(popNode[0])) continue
val weight = popNode[1]
result = weight
visited.add(src)
if(!graph.containsKey(src)) continue
graph[src]?.forEach{edgeArr->
minHeapOfWeight.add(intArrayOf(edgeArr[0], weight + edgeArr[1]))
}
}
if(visited.size == n){
return result
}
return -1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment