Created
April 9, 2023 15:10
-
-
Save saldisobi/be4e1c20298af3db597b44bab763fa8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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