缘起

最近阅读<<我的第一本算法书>>(【日】石田保辉;宫崎修一)
本系列笔记拟采用golang练习之

A*(A-Star)算法

  1. A*(A-Star)算法也是一种在图中求解最短路径问题的算法,
  2. 由狄克斯特拉算法发展而来。
  3. A*算法不仅会考虑从起点到候补顶点的距离,
  4. 还会考虑从当前所在顶点到终点的估算距离。
  5. 距离估算值越接近当前顶点到终点的实际值,
  6. A*算法的搜索效率也就越高.
  7. 当距离估算值小于实际距离时,
  8. 是一定可以得到正确答案的.
  9. A*算法在游戏编程中经常被用于计算敌人追赶玩家时的行动路线等.
  10. 摘自 <<我的第一本算法书>> 【日】石田保辉;宫崎修一

场景

如下图, 某游戏中, 地图是网格状的, 我方在S点, 敌人在G点, 空白区域是湖泊/树林等不可到达区域:
image.png
现在需要追击敌人, 因此需要计算S点到G点的最短行进路线.
A*算法是以狄克斯特拉算法为基础, 区别是在计算候选节点的权重时, 需要同时考虑测量权重和估算权重.
此场景中, 使用S点到G点坐标的直线距离作为估算权重.
估算权重的作用就像牵引风筝的绳子, 使得每次选取的候选节点, 尽量是靠往终点方向.
image.png

流程

  1. 给定若干顶点, 以及顶点间的若干条边, 寻找从指定起点srcNode到指定终点dstNode的最小权重路径
  2. 设定srcNode的权重为0, 其他顶点的权重为无穷大
  3. 计算所有节点到dstNode节点的估算距离, 以x,y坐标的直线距离作为估算值
  4. 节点.总权重 = 节点.测量权重 + 节点.估算权重
  5. 将srcNode节点送入候选堆
  6. for 候选堆不为空:
    1. 从候选堆pop顶点node, node是总权重最小的候选节点
    2. 如果node.id == dstNode.id, 循环结束
    3. 遍历从node出发的所有边, 将边的终点to的测量权重, 更新为min(to.测量权重, node.测量权重+边.权重)
    4. 如果to.测量权重 > node.测量权重+边.权重, 说明更新有效
    5. 如果更新有效, 判断to是否在堆中, 如果是, 则上浮以维护堆秩序, 否则, 将to节点push入候选堆
  7. 判断dstNode的测量权重是否被更新(!=无穷大), 如果是则说明存在最短路径
  8. 反向查找最短路径:
    1. 设定当前节点current = 终点
    2. push节点current进路径队列
    3. 遍历终点为current的边, 查找符合条件的node:边的起点.测量权重 = current.测量权重-边.权重
    4. push节点node进路径队列
    5. 循环1-4, 直到current == srcNode, 查找完成

设计

  • INode: 顶点接口, 支持xy坐标和估算权重
  • ILine: 边接口
  • IPathFinder: 最短路径查找算法接口
  • IComparator: 顶点比较接口
  • IHeap: 顶点堆接口
  • tNode: 顶点, 实现INode
  • tLine: 边, 实现ILine
  • tNodeWeightComparator: 基于权重的顶点比较器, 实现IComparator接口
  • tArrayHeap: 堆的实现
  • tAStarPathFinder: A*算法的实现, 使用xy坐标的直线距离作为估算权重

单元测试

a_star_finder_test.go

  1. package graph
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. )
  7. import astar "learning/gooop/graph/a_star"
  8. func Test_AStarFinder(t *testing.T) {
  9. fnAssertTrue := func(b bool, msg string) {
  10. if !b {
  11. t.Fatal(msg)
  12. }
  13. }
  14. // 设定顶点
  15. nodes := []astar.INode {
  16. astar.NewNode("11", 1, 1),
  17. astar.NewNode("21", 2, 1),
  18. astar.NewNode("31", 3, 1),
  19. astar.NewNode("12", 1, 2),
  20. astar.NewNode("32", 3, 2),
  21. astar.NewNode("13", 1, 3),
  22. astar.NewNode("33", 3, 3),
  23. astar.NewNode("43", 4, 3),
  24. astar.NewNode("53", 5, 3),
  25. astar.NewNode("63", 6, 3),
  26. astar.NewNode("73", 7, 3),
  27. astar.NewNode("14", 1, 4),
  28. astar.NewNode("34", 3, 4),
  29. astar.NewNode("74", 7, 4),
  30. astar.NewNode("15", 1, 5),
  31. astar.NewNode("35", 3, 5),
  32. astar.NewNode("55", 5, 5),
  33. astar.NewNode("65", 6, 5),
  34. astar.NewNode("75", 7, 5),
  35. astar.NewNode("16", 1, 6),
  36. astar.NewNode("36", 3, 6),
  37. astar.NewNode("56", 5, 6),
  38. astar.NewNode("17", 1, 7),
  39. astar.NewNode("27", 2, 7),
  40. astar.NewNode("37", 3, 7),
  41. astar.NewNode("47", 4, 7),
  42. astar.NewNode("57", 5, 7),
  43. astar.NewNode("67", 6, 7),
  44. astar.NewNode("77", 7, 7),
  45. }
  46. // 为相邻点创建边
  47. var lines []astar.ILine
  48. mapNodes := make(map[string]astar.INode, len(nodes))
  49. for _,it := range nodes {
  50. k := fmt.Sprintf("%v,%v", it.GetX(), it.GetY())
  51. mapNodes[k] = it
  52. }
  53. for _,it := range nodes {
  54. if up,ok := mapNodes[fmt.Sprintf("%v,%v", it.GetX(), it.GetY() - 1)];ok {
  55. lines = append(lines, astar.NewLine(it.ID(), up.ID(), 1), astar.NewLine(up.ID(), it.ID(), 1))
  56. }
  57. if down,ok := mapNodes[fmt.Sprintf("%v,%v", it.GetX(), it.GetY() + 1)];ok {
  58. lines = append(lines, astar.NewLine(it.ID(), down.ID(), 1), astar.NewLine(down.ID(), it.ID(), 1))
  59. }
  60. if left,ok := mapNodes[fmt.Sprintf("%v,%v", it.GetX()-1, it.GetY())];ok {
  61. lines = append(lines, astar.NewLine(it.ID(), left.ID(), 1), astar.NewLine(left.ID(), it.ID(), 1))
  62. }
  63. if right,ok := mapNodes[fmt.Sprintf("%v,%v", it.GetX()+1, it.GetY())];ok {
  64. lines = append(lines, astar.NewLine(it.ID(), right.ID(), 1), astar.NewLine(right.ID(), it.ID(), 1))
  65. }
  66. }
  67. // a*算法 查找最短路径
  68. ok,path := astar.AStarPathFinder.FindPath(nodes, lines, "33", "77")
  69. if !ok {
  70. t.Fatal("failed to find min path")
  71. }
  72. fnPathToString := func(nodes []astar.INode) string {
  73. items := make([]string, len(nodes))
  74. for i,it := range nodes {
  75. items[i] = fmt.Sprintf("%s", it)
  76. }
  77. return strings.Join(items, " ")
  78. }
  79. pathString := fnPathToString(path)
  80. t.Log(pathString)
  81. fnAssertTrue(pathString == "33(0+6) 34(1+5) 35(2+4) 36(3+4) 37(4+4) 47(5+3) 57(6+2) 67(7+1) 77(8+0)", "incorrect path")
  82. }

测试输出

  1. $ go test -v a_star_finder_test.go
  2. === RUN Test_AStarFinder
  3. a_star_finder_test.go:96: 33(0+6) 34(1+5) 35(2+4) 36(3+4) 37(4+4) 47(5+3) 57(6+2) 67(7+1) 77(8+0)
  4. --- PASS: Test_AStarFinder (0.00s)
  5. PASS
  6. ok command-line-arguments 0.002s

INode.go

顶点接口, 支持xy坐标和估算权重

  1. package a_star
  2. type INode interface {
  3. ID() string
  4. GetX() int
  5. GetY() int
  6. SetX(int)
  7. SetY(int)
  8. SetEstimatedWeight(int)
  9. SetMeasuredWeight(int)
  10. GetMeasuredWeight() int
  11. GetTotalWeight() int
  12. }
  13. const MaxWeight = int(0x7fffffff_00000000)

ILine.go

边接口

  1. package a_star
  2. type ILine interface {
  3. From() string
  4. To() string
  5. Weight() int
  6. }

IPathFinder.go

最短路径查找算法接口

  1. package a_star
  2. type IPathFinder interface {
  3. FindPath(nodes []INode, lines []ILine, from string, to string) (bool,[]INode)
  4. }

IComparator.go

顶点比较接口

  1. package a_star
  2. type IComparator interface {
  3. Less(a interface{}, b interface{}) bool
  4. }

IHeap.go

顶点堆接口

  1. package a_star
  2. type IHeap interface {
  3. Size() int
  4. IsEmpty() bool
  5. IsNotEmpty() bool
  6. Push(node interface{})
  7. Pop() (bool, interface{})
  8. IndexOf(node interface{}) int
  9. ShiftUp(i int)
  10. }

tNode.go

顶点, 实现INode

  1. package a_star
  2. import "fmt"
  3. type tNode struct {
  4. id string
  5. x int
  6. y int
  7. measuredWeight int
  8. estimatedWeight int
  9. }
  10. func NewNode(id string, x int, y int) INode {
  11. return &tNode{
  12. id,x, y, MaxWeight,0,
  13. }
  14. }
  15. func (me *tNode) ID() string {
  16. return me.id
  17. }
  18. func (me *tNode) GetX() int {
  19. return me.x
  20. }
  21. func (me *tNode) GetY() int {
  22. return me.y
  23. }
  24. func (me *tNode) SetX(x int) {
  25. me.x = x
  26. }
  27. func (me *tNode) SetY(y int) {
  28. me.y = y
  29. }
  30. func (me *tNode) SetEstimatedWeight(w int) {
  31. me.estimatedWeight = w
  32. }
  33. func (me *tNode) SetMeasuredWeight(w int) {
  34. me.measuredWeight = w
  35. }
  36. func (me *tNode) GetMeasuredWeight() int {
  37. return me.measuredWeight
  38. }
  39. func (me *tNode) GetTotalWeight() int {
  40. return me.estimatedWeight + me.measuredWeight
  41. }
  42. func (me *tNode) String() string {
  43. return fmt.Sprintf("%s(%v+%v)", me.id, me.measuredWeight, me.estimatedWeight)
  44. }

tLine.go

边, 实现ILine

  1. package a_star
  2. type tLine struct {
  3. from string
  4. to string
  5. weight int
  6. }
  7. func NewLine(from string, to string, weight int) ILine {
  8. return &tLine{
  9. from,to,weight,
  10. }
  11. }
  12. func (me *tLine) From() string {
  13. return me.from
  14. }
  15. func (me *tLine) To() string {
  16. return me.to
  17. }
  18. func (me *tLine) Weight() int {
  19. return me.weight
  20. }

tNodeWeightComparator.go

基于权重的顶点比较器, 实现IComparator接口

  1. package a_star
  2. import "errors"
  3. type tNodeWeightComparator struct {
  4. }
  5. func newNodeWeightComparator() IComparator {
  6. return &tNodeWeightComparator{
  7. }
  8. }
  9. func (me *tNodeWeightComparator) Less(a interface{}, b interface{}) bool {
  10. if a == nil || b == nil {
  11. panic(gNullArgumentError)
  12. }
  13. n1 := a.(INode)
  14. n2 := b.(INode)
  15. return n1.GetTotalWeight() <= n2.GetTotalWeight()
  16. }
  17. var gNullArgumentError = errors.New("null argument error")

tArrayHeap.go

堆的实现

  1. package a_star
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. )
  7. type tArrayHeap struct {
  8. comparator IComparator
  9. items []interface{}
  10. size int
  11. version int64
  12. }
  13. func newArrayHeap(comparator IComparator) IHeap {
  14. return &tArrayHeap{
  15. comparator: comparator,
  16. items: make([]interface{}, 0),
  17. size: 0,
  18. version: 0,
  19. }
  20. }
  21. func (me *tArrayHeap) Size() int {
  22. return me.size
  23. }
  24. func (me *tArrayHeap) IsEmpty() bool {
  25. return me.size <= 0
  26. }
  27. func (me *tArrayHeap) IsNotEmpty() bool {
  28. return !me.IsEmpty()
  29. }
  30. func (me *tArrayHeap) Push(value interface{}) {
  31. me.version++
  32. me.ensureSize(me.size + 1)
  33. me.items[me.size] = value
  34. me.size++
  35. me.ShiftUp(me.size - 1)
  36. me.version++
  37. }
  38. func (me *tArrayHeap) ensureSize(size int) {
  39. for ;len(me.items) < size; {
  40. me.items = append(me.items, nil)
  41. }
  42. }
  43. func (me *tArrayHeap) parentOf(i int) int {
  44. return (i - 1) / 2
  45. }
  46. func (me *tArrayHeap) leftChildOf(i int) int {
  47. return i*2 + 1
  48. }
  49. func (me *tArrayHeap) rightChildOf(i int) int {
  50. return me.leftChildOf(i) + 1
  51. }
  52. func (me *tArrayHeap) last() (i int, v interface{}) {
  53. if me.IsEmpty() {
  54. return -1, nil
  55. }
  56. i = me.size - 1
  57. v = me.items[i]
  58. return i,v
  59. }
  60. func (me *tArrayHeap) IndexOf(node interface{}) int {
  61. n := -1
  62. for i,it := range me.items {
  63. if it == node {
  64. n = i
  65. break
  66. }
  67. }
  68. return n
  69. }
  70. func (me *tArrayHeap) ShiftUp(i int) {
  71. if i <= 0 {
  72. return
  73. }
  74. v := me.items[i]
  75. pi := me.parentOf(i)
  76. pv := me.items[pi]
  77. if me.comparator.Less(v, pv) {
  78. me.items[pi], me.items[i] = v, pv
  79. me.ShiftUp(pi)
  80. }
  81. }
  82. func (me *tArrayHeap) Pop() (bool, interface{}) {
  83. if me.IsEmpty() {
  84. return false, nil
  85. }
  86. me.version++
  87. top := me.items[0]
  88. li, lv := me.last()
  89. me.items[0] = nil
  90. me.size--
  91. if me.IsEmpty() {
  92. return true, top
  93. }
  94. me.items[0] = lv
  95. me.items[li] = nil
  96. me.shiftDown(0)
  97. me.version++
  98. return true, top
  99. }
  100. func (me *tArrayHeap) shiftDown(i int) {
  101. pv := me.items[i]
  102. ok, ci, cv := me.minChildOf(i)
  103. if ok && me.comparator.Less(cv, pv) {
  104. me.items[i], me.items[ci] = cv, pv
  105. me.shiftDown(ci)
  106. }
  107. }
  108. func (me *tArrayHeap) minChildOf(p int) (ok bool, i int, v interface{}) {
  109. li := me.leftChildOf(p)
  110. if li >= me.size {
  111. return false, 0, nil
  112. }
  113. lv := me.items[li]
  114. ri := me.rightChildOf(p)
  115. if ri >= me.size {
  116. return true, li, lv
  117. }
  118. rv := me.items[ri]
  119. if me.comparator.Less(lv, rv) {
  120. return true, li, lv
  121. } else {
  122. return true, ri, rv
  123. }
  124. }
  125. func (me *tArrayHeap) String() string {
  126. level := 0
  127. lines := make([]string, 0)
  128. lines = append(lines, "")
  129. for {
  130. n := 1<<level
  131. min := n - 1
  132. max := n + min - 1
  133. if min >= me.size {
  134. break
  135. }
  136. line := make([]string, 0)
  137. for i := min;i <= max;i++ {
  138. if i >= me.size {
  139. break
  140. }
  141. line = append(line, fmt.Sprintf("%4d", me.items[i]))
  142. }
  143. lines = append(lines, strings.Join(line, ","))
  144. level++
  145. }
  146. return strings.Join(lines, "\n")
  147. }
  148. var gNoMoreElementsError = errors.New("no more elements")

tAStarPathFinder.go

A*算法的实现, 使用xy坐标的直线距离作为估算权重

  1. package a_star
  2. import "math"
  3. type tAStarPathFinder struct {
  4. }
  5. func newAStarPathFinder() IPathFinder {
  6. return &tAStarPathFinder{}
  7. }
  8. func (me *tAStarPathFinder) FindPath(nodes []INode, lines []ILine, srcID string, dstID string) (bool,[]INode) {
  9. // 节点索引
  10. mapNodes := make(map[string]INode, 0)
  11. for _,it := range nodes {
  12. mapNodes[it.ID()] = it
  13. }
  14. srcNode, ok := mapNodes[srcID]
  15. if !ok {
  16. return false, nil
  17. }
  18. dstNode,ok := mapNodes[dstID]
  19. if !ok {
  20. return false, nil
  21. }
  22. // 边的索引
  23. mapFromLines := make(map[string][]ILine, 0)
  24. mapToLines := make(map[string][]ILine, 0)
  25. for _, it := range lines {
  26. if v,ok := mapFromLines[it.From()];ok {
  27. mapFromLines[it.From()] = append(v, it)
  28. } else {
  29. mapFromLines[it.From()] = []ILine{ it }
  30. }
  31. if v,ok := mapToLines[it.To()];ok {
  32. mapToLines[it.To()] = append(v, it)
  33. } else {
  34. mapToLines[it.To()] = []ILine{ it }
  35. }
  36. }
  37. for _,it := range nodes {
  38. // 设置src节点的weight为0, 其他节点的weight为MaxWeight
  39. if it.ID() == srcID {
  40. it.SetMeasuredWeight(0)
  41. } else {
  42. it.SetMeasuredWeight(MaxWeight)
  43. }
  44. // 计算每个节点到dst节点的估算距离
  45. if it.ID() == dstID {
  46. it.SetEstimatedWeight(0)
  47. } else {
  48. it.SetEstimatedWeight(me.distance(it.GetX(), it.GetY(), dstNode.GetY(), dstNode.GetY()))
  49. }
  50. }
  51. // 将起点push到堆
  52. heap := newArrayHeap(newNodeWeightComparator())
  53. heap.Push(srcNode)
  54. // 遍历候选节点
  55. for heap.IsNotEmpty() {
  56. _, top := heap.Pop()
  57. from := top.(INode)
  58. if from.ID() == dstID {
  59. break
  60. }
  61. links, ok := mapFromLines[from.ID()]
  62. if ok {
  63. for _,line := range links {
  64. if to,ok := mapNodes[line.To()];ok {
  65. if me.updateMeasuredWeight(from, to, line) {
  66. n := heap.IndexOf(to)
  67. if n >= 0 {
  68. heap.ShiftUp(n)
  69. } else {
  70. heap.Push(to)
  71. }
  72. }
  73. }
  74. }
  75. }
  76. }
  77. // 逆向查找最短路径
  78. if dstNode.GetMeasuredWeight() >= MaxWeight {
  79. return false, nil
  80. }
  81. path := []INode{ dstNode }
  82. current := dstNode
  83. maxRound := len(lines)
  84. for ;current != srcNode && maxRound > 0;maxRound-- {
  85. linkedLines, _ := mapToLines[current.ID()]
  86. for _,line := range linkedLines {
  87. from, _ := mapNodes[line.From()]
  88. if from.GetMeasuredWeight() == current.GetMeasuredWeight() - line.Weight() {
  89. current = from
  90. path = append(path, from)
  91. }
  92. }
  93. }
  94. if current != srcNode {
  95. return false, nil
  96. }
  97. me.reverse(path)
  98. return true, path
  99. }
  100. func (me *tAStarPathFinder) distance(x0, y0, x1, y1 int) int {
  101. dx := x0 - x1
  102. dy := y0 - y1
  103. return int(math.Round(math.Sqrt(float64(dx * dx + dy * dy))))
  104. }
  105. func (me *tAStarPathFinder) reverse(nodes []INode) {
  106. for i,j := 0, len(nodes)-1;i < j;i,j=i+1,j-1 {
  107. nodes[i], nodes[j] = nodes[j], nodes[i]
  108. }
  109. }
  110. func (me *tAStarPathFinder) updateMeasuredWeight(from INode, to INode, line ILine) bool {
  111. w := me.min(from.GetMeasuredWeight() + line.Weight(), to.GetMeasuredWeight())
  112. if to.GetMeasuredWeight() > w {
  113. to.SetMeasuredWeight(w)
  114. return true
  115. }
  116. return false
  117. }
  118. func (me *tAStarPathFinder) min(a, b int) int {
  119. if a <= b {
  120. return a
  121. }
  122. return b
  123. }
  124. var AStarPathFinder = newAStarPathFinder()

(end)