Skip to content

Commit

Permalink
Create 1514-path-with-maximum-probability.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored May 17, 2023
1 parent c963573 commit cd54717
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions kotlin/1514-path-with-maximum-probability.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
val adj = HashMap<Int, ArrayList<Pair<Int, Double>>>().apply {
for ((i, edge) in edges.withIndex()) {
val (u, v) = edge
this[u] = getOrDefault(u, ArrayList<Pair<Int, Double>>()).apply { add(v to succProb[i]) }
this[v] = getOrDefault(v, ArrayList<Pair<Int, Double>>()).apply { add(u to succProb[i]) }
}
}

val visited = HashSet<Int>()
val minHeap = PriorityQueue<Pair<Int, Double>>{ a, b ->
if (a.second < b.second) 1 else -1
}

with (minHeap) {
add(start to 1.0)

while (isNotEmpty()) {
val (node, currCost) = poll()
visited.add(node)

if (node == end) return currCost

adj[node]?.forEach {
if (it.first !in visited) {
add(it.first to currCost * it.second)
}
}
}
}

return 0.0
}
}

0 comments on commit cd54717

Please sign in to comment.