여러 시작점과 여러 끝점이있는 일종의 미로를 해결하기 위해 Python으로 스크립트를 작성하려고합니다. 시작 지점에서 직선을 따라 올바른 경로가 얻어집니다. 예를 들어Python : "n-to-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")
입력 이미지가 이와 같은 흑백 이미지는
나는 미국을 생각 해왔다. 비슷하지만 대각선 방향에 더 상응하는 4 방향 추가.
좋은 결과를 얻으려면 다른 아이디어가 필요하십니까?
이 흥미로운 문제처럼 보인다. 핵심 통찰력은 "직선"이 교차점을 의미하고 반드시 추기경 방향을 의미하지 않는다고 생각합니다. 나는 지점 X에서 시작하여 경로가 무효화 될 때까지 직선을 따라 이동하여 새로운 라인을 선택하는 구현을 가지고 놀고있다. 또 다른 흥미로운 방법은 라인 디텍터를 사용하고 라인 네트워크를 구축하는 것입니다. – Chris