mirror of
https://github.com/onyx-and-iris/aoc2023.git
synced 2024-11-15 15:10:49 +00:00
50 lines
803 B
Go
50 lines
803 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"container/heap"
|
||
|
)
|
||
|
|
||
|
// pqueue implements the heap.Interface interface
|
||
|
// it represents a min heap priority queue
|
||
|
type pqueue []*node
|
||
|
|
||
|
func newPriorityQueue() *pqueue {
|
||
|
pq := make(pqueue, 0)
|
||
|
return &pq
|
||
|
}
|
||
|
|
||
|
func (pq pqueue) Len() int {
|
||
|
return len(pq)
|
||
|
}
|
||
|
|
||
|
func (pq *pqueue) Push(x interface{}) {
|
||
|
n := len(*pq)
|
||
|
node := x.(*node)
|
||
|
node.index = n
|
||
|
*pq = append(*pq, node)
|
||
|
}
|
||
|
|
||
|
func (pq *pqueue) Pop() interface{} {
|
||
|
old := *pq
|
||
|
n := len(old)
|
||
|
node := old[n-1]
|
||
|
node.index = -1
|
||
|
*pq = old[0 : n-1]
|
||
|
return node
|
||
|
}
|
||
|
|
||
|
func (pq *pqueue) Update(node *node, value int) {
|
||
|
node.cost = value
|
||
|
heap.Fix(pq, node.index)
|
||
|
}
|
||
|
|
||
|
func (pq pqueue) Less(i, j int) bool {
|
||
|
return pq[i].cost < pq[j].cost
|
||
|
}
|
||
|
|
||
|
func (pq pqueue) Swap(i, j int) {
|
||
|
pq[i], pq[j] = pq[j], pq[i]
|
||
|
pq[i].index = i
|
||
|
pq[j].index = j
|
||
|
}
|