之前发表一个A*的python实现,连接:点击打开链接
最近正在学习Go语言,基本的语法等东西已经掌握了。但是纸上得来终觉浅,绝知此事要躬行嘛。必要的练手是一定要做的。正好离写python版的A*不那么久远。这个例子复杂度中等。还可以把之前用python实现是没有考虑的部分整理一下。
这一版的GO实现更加模块化了,同时用二叉堆来保证了openlist的查找性能。可以说离应用到实现工程中的要求差距不太远了。
如果有谁觉得代码有用的话可以拿去用,但是必须通知我一下。这个要求不高吧。
package main
import (
"container/heap"
"fmt"
"math"
"strings"
)
import "strconv"
type OpenList []*_AstarPoint
func (self OpenList) Len() int { return len(self) }
func (self OpenList) Less(i, j int) bool { return self[i].fVal < self[j].fVal }
func (self OpenList) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (this *OpenList) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*this = append(*this, x.(*_AstarPoint))
}
func (this *OpenList) Pop() interface{} {
old := *this
n := len(old)
x := old[n-1]
*this = old[0 : n-1]
return x
}
type _Point struct {
x int
y int
view string
}
//========================================================================================
// 保存地图的基本信息
type Map struct {
points [][]_Point
blocks map[string]*_Point
maxX int
maxY int
}
func NewMap(charMap []string) (m Map) {
m.points = make([][]_Point, len(charMap))
m.blocks = make(map[string]*_Point, len(charMap)*2)
for x, row := range charMap {
cols := strings.Split(row, " ")
m.points[x] = make([]_Point, len(cols))
for y, view := range cols {
m.points[x][y] = _Point{x, y, view}
if view == "X" {
m.blocks[pointAsKey(x, y)] = &m.points[x][y]