在春节放假前两天我偶然看到了A*算法,感觉挺有意思。正好放假前也没有什么事情,就花了一个下午写出算法的骨架,节后又花了半天时间完善屏幕输出的细节并且调试完成。
该实现只是一时兴起的随手而作,没有考虑性能和扩展性等问题。正在学习A*的朋友可以拿去随便折腾。
Email: wang.zhigang@hotmail.com
代码的运行效果如下:
#!/usr/bin/python
# vim:set fileencoding=utf-8
# 在春节放假前两天我偶然看到了A*算法,感觉挺有意思。正好放假前
# 也没有什么事情,就花了一个下午写出算法的骨架,节后又花了半天
# 时间完善屏幕输出的细节并且调试完成。
# 该实现只是一时兴起的随手而作,没有考虑性能和扩展性等问题。正
# 在学习A*的朋友可以拿去随便折腾。
# email: wang.zhigang@hotmail.com
import sys
_2dmap = []
start = None
end = None
open_list = {}
close_list = {}
map_border = ()
class Node:
def __init__(this, father, x, y):
if x < 0 or x >= map_border[0] or y < 0 or y >= map_border[1]:
raise Exception("node position can't beyond the border!")
this.father = father
this.x = x
this.y = y
if father != None:
G2father = calc_G(father, this)
if not G2father:
raise Exception("father is not valid!")
this.G = G2father + father.G
this.H = calc_H(this, end)
this.F = this.G + this.H
else:
this.G = 0
this.H = 0
this.F = 0
def reset_father(this, father, new_G):
if father != None:
this.G = new_G
this.F = this.G + this.H
this.father = father
def calc_G(node1, node2):
x1 = abs(node1.x-node2.x)
y1 = abs(node1.y-node2.y)
if (x1== 1 and y1 == 0):
return 10