Skip to content

Instantly share code, notes, and snippets.

@GregoryMaks
Created February 17, 2026 13:58
Show Gist options
  • Select an option

  • Save GregoryMaks/d25b9dc06e9ffb640e668828846f7b82 to your computer and use it in GitHub Desktop.

Select an option

Save GregoryMaks/d25b9dc06e9ffb640e668828846f7b82 to your computer and use it in GitHub Desktop.
class Solution {
func networkDelayTime(_ times: [[Int]], _ n: Int, _ k: Int) -> Int {
var graph: [Int: [(Int, Int)]] = [:]
for time in times {
var edges = graph[time[0]] ?? []
edges.append((time[1], time[2]))
graph[time[0]] = edges
}
struct HeapNode: Comparable {
let n: Int
let t: Int
static func < (l: Self, r: Self) -> Bool { l.t < r.t }
}
var nodeTimes: [Int] = .init(repeating: Int.max, count: n+1) // indexing starts from 1 in the conditions
var nodesLeft = n
var heap: Heap<HeapNode> = [.init(n: k, t: 0)]
while let node = heap.popMin() {
if nodeTimes[node.n] == Int.max {
nodesLeft -= 1
if nodesLeft == 0 { return node.t }
}
nodeTimes[node.n] = node.t
guard let edges = graph[node.n] else { continue }
for e in edges {
let t = node.t+e.1
if nodeTimes[e.0] > t {
heap.insert(.init(n: e.0, t: t))
}
}
}
return -1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment