我想在Python中編寫一個腳本來解決一種具有多個起點和多個終點的迷宮。從起點開始沿着直線獲得正確的路徑。Python:解決「n對n」的迷宮
例如,具有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")
輸入圖像是這樣一個黑白圖像:
其中產量:
我想到了usi類似的東西,但增加4個方向更對應的對角線方向。
任何其他想法,以獲得良好的結果?
這似乎是一個有趣的問題。我認爲關鍵的見解是「直線」意味着通過交叉點,而不一定是在主要方向。我正在玩一個從X點開始的實現,並沿着一條直線移動,直到路徑沿着該線無效,此時它將選擇一條新線。另一個有趣的方法是使用線路檢測器並建立線路網絡。 – Chris 2014-10-23 21:34:39