我正在尝试用Python编写脚本解决一种迷宫问题,该问题有多个起点和终点。正确的路径是从起点沿直线到达终点。
例如,一个具有4条路径的迷宫: 起初我想使用左/右手定则,但由于迷宫的特性,这并没有太多意义。我尝试设计了一个算法,按照4个方向(上、下、左、右)直线行进。
目前我的算法如下:
输入图像是一张黑白图像,就像这一张:。最终结果如下:。我考虑过类似的方法,但同时添加了四个对角方向。还有别的想法可以得到好的结果吗?
例如,一个具有4条路径的迷宫: 起初我想使用左/右手定则,但由于迷宫的特性,这并没有太多意义。我尝试设计了一个算法,按照4个方向(上、下、左、右)直线行进。
目前我的算法如下:
from PIL import Image
UP='up'
DOWN='down'
LEFT='left'
RIGHT='right'
directionOld=RIGHT
def checkAdjacents(im,x,y):
matrix=[]
for Y in range(y-1,y+2):
r=[]
for X in range(x-1,x+2):
if im.getpixel((X,Y))==255:
r.append(True)
else:
r.append(False)
matrix.append(r)
return matrix
def testDirection(adj,direction):
if direction==UP and adj[0][1]:
return False
if direction==LEFT and adj[1][0]:
return False
if direction==RIGHT and adj[1][2]:
return False
if direction==DOWN and adj[2][1]:
return False
return True
def changeDirection(adj,direction):
if direction==UP or direction==DOWN:
if adj[1][2]:
direction=RIGHT
else:
direction=LEFT
else:
if adj[2][1]:
direction=DOWN
else:
direction=UP
return direction
def move(im,im2,x,y,directionOld,color):
im2.putpixel((x,y),color)
adj=checkAdjacents(im,x,y)
change=testDirection(adj,directionOld)
directionNew=directionOld
if change:
directionNew=changeDirection(adj,directionOld)
print "New direction ->",directionNew
if directionNew==UP:
y-=1
elif directionNew==DOWN:
y+=1
elif directionNew==RIGHT:
x+=1
else:
x-=1
return (x,y,directionNew)
image_file = Image.open("maze.png") # open colour image
im = image_file.convert('1') # convert image to black and white
im.save("2.png")
im2=im.copy() #duplicate to store results
im2=im2.convert("RGB") #results in color
paths=[(114,110,(255,0,255)),#Path1
(114,178,(255,0,0)),#Path2
(114,250,(0,255,0)),#Path3
(114,321,(0,0,255)),#Path4
]
for path in paths:
print "------------------------------------"
print "----------------Path"+str(paths.index(path))+"---------------"
print "------------------------------------"
x,y,color=path
for i in range(0,750):#number of steps
x,y,directionOld=move(im,im2,x,y,directionOld,color)
im2.save("maze_solved.png")
输入图像是一张黑白图像,就像这一张:。最终结果如下:。我考虑过类似的方法,但同时添加了四个对角方向。还有别的想法可以得到好的结果吗?