带剪枝的启发式搜索,25年前学的手艺,还没丢
不过干这个活,python真不如C/pascal顺手,性能就更不用提了。
import numpy as np
import queue
N=4
A0=np.array([11,15,8,6,3,5,12,2,4,16,9,14,10,7,1,13])-1
p0=list(A0).index(N*N-1)
obj=np.array(range(0,N*N))
ox=obj%4
oy=obj//4
def dist(a):
return np.sum(np.abs(a//N-oy)+np.abs(a%N-ox))
def pr(nd):
path=[]
while len(nd)>1:
path.insert(0,nd)
nd=nd[1]
for i,node in enumerate(path):
print (i,node[4],' ->',node[3]+1)
def go():
node0=(dist(A0),(0,),p0,A0,0,0) #parent,pos,A
nodes=set()
q=queue.PriorityQueue()
q.put(node0)
best=None
while not q.empty():
nd=q.get()
nodes.add(tuple(nd[3]))
if len(nodes)%1000==0:
print(len(nodes),nd[0])
g,prt,p,a,dd,ee=nd
if dist(a)==0:
pr(nd)
best=nd
#break
if best and ee+g/2>best[5]:
continue
for d in [1,-1,N,-N]:
p2=p+d
if p2>=N*N or p2<0 :
continue
a2=np.copy(a)
t=a2[p];a2[p]=a2[p2];a2[p2]=t
if tuple(a2) in nodes:
continue
nd2=(dist(a2)+ee/100,nd,p2,a2,d,nd[5]+1)
q.put(nd2)
go()