node_heap.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package astar6
  2. // ============ 优先队列实现 ============
  3. // 实现container/heap接口,用于高效获取f值最小的节点
  4. // 相比sort.Slice,heap在动态插入/删除场景下性能更优
  5. // Push/Pop复杂度: O(log n)
  6. // 使用索引堆优化,updateHeap复杂度从O(n)优化为O(log n)
  7. // heapItem 堆中的元素(索引堆实现)
  8. type heapItem struct {
  9. node *Node // 节点指针
  10. f int32 // f = g + h
  11. index int // 在堆中的索引位置,用于O(1)定位和O(log n)更新
  12. }
  13. // nodeHeap 最小堆,f值最小的节点在堆顶
  14. type nodeHeap []*heapItem
  15. // Len 返回堆的大小
  16. func (h nodeHeap) Len() int { return len(h) }
  17. // Less 比较函数,f值小的优先级高
  18. func (h nodeHeap) Less(i, j int) bool { return h[i].f < h[j].f }
  19. // Swap 交换两个元素,同时更新索引
  20. func (h nodeHeap) Swap(i, j int) {
  21. h[i], h[j] = h[j], h[i]
  22. h[i].index = i
  23. h[j].index = j
  24. }
  25. // Push 向堆中添加元素
  26. func (h *nodeHeap) Push(x interface{}) {
  27. item := x.(*heapItem)
  28. item.index = len(*h)
  29. *h = append(*h, item)
  30. }
  31. // Pop 从堆中取出最小元素
  32. func (h *nodeHeap) Pop() interface{} {
  33. old := *h
  34. n := len(old)
  35. item := old[n-1]
  36. old[n-1] = nil // 置nil避免内存泄漏
  37. *h = old[0 : n-1]
  38. return item
  39. }