Python递归迷宫求解器永远不会回溯

时间:2020-04-04 15:10:09

标签: python recursion python-imaging-library

我有一个带有一个图像(PNG,200x200)的递归迷宫求解器,我尝试使用try / except来打印异常,但是什么也不会打印。

递归函数

("कोरोना के से में 932 की हुई. साथ ", "वायरस स्पेन लोगों इसके स्पेन मरने ", "संक्रमण मौत में की संख्या हज़ार ", "शुक्रवार वालों 10 पहुंच है. के ", "ही 935 इटली स्पेन का देश जहां ", "कुल बाद दूसरा कोरोना से ज़्यादा ", "गई है सबसे हुई ", "दुनिया वायरस मौतें हैं.")

isValid检查二维数组在传入位置是否在其范围内是否有“ W”(对于白​​色像素)

def solveRecursiveMaze(arr,x,y):
    successful = False
    if (x,y) == getExitPoint():
        successful = True
    elif isValid(arr,x,y):
        arr[x][y] = "V" #set to V to show it's a visited path
        successful = solveRecursiveMaze(arr, x-1, y)    
        if not successful:
            successful = solveRecursiveMaze(arr, x, y+1)
        if not successful:
            successful = solveRecursiveMaze(arr, x+1, y)
        if not successful:
            successful = solveRecursiveMaze(arr, x, y-1)
    if successful:
        arr[x][y] = "P" #Mark as P to show it's a valid pa
    return successful

getExitPoint返回在迷宫出口处找到的点的x,y(像素)

def isValid(arr,x,y):
    if x < len(arr) and y < len(arr) and x >= 0 and y >= 0:
         if arr[x][y] == "W":
             return True
    return False

这就是我将图像转换为2D数组的方式

def getExitPoint():
     x = crop.size[0] - 1
     for y in range(0, crop.size[1]):
         if(crop.getpixel((x,y)) == (255,255,255)):
             return x,y
         if(crop.getpixel((y,x)) == (255,255,255)):
             return y,x
  • 应该做的是将图像转换为2D数组,然后递归遍历(使用回溯)以寻找成功的路径,然后在路径上绘制一条红线。

该脚本在此图像上不起作用,它每次都在像素X = 76,y = 153处停止,并且我不确定该怎么做/我在做什么错

The script does not work on this image

边界为1px,路径为1px。没有任何错误,堆栈跟踪,异常或任何引发的事件。递归只是停止,程序退出了。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您的代码有很多问题,但是我认为正在发生的事情是您超出了递归限制。您的迷宫很大而且很复杂。我需要使用4000(对我来说,1000是默认值,而3000不够大)。

不确定所使用的图像库是什么;我使用了PIL.Image

您输入的图像实际上是203x203,因此很难找到入口和出口。我假设入口在顶部或左侧,出口在右侧或底部。

enter image description here

import sys
import argparse
import PIL.Image
import os

colors = {
    'white' : (255, 255, 255),
    'black' : (0, 0, 0),
    'red'   : (128, 0, 0),
    'green' : (0, 255, 0) }


def isValid(image, x, y):
    if x < image.size[0] and y < image.size[1] and x >= 0 and y >= 0:
        if image.getpixel((x, y)) == colors['white']:
            return True
    return False


def getEntryPoint(image):
    # Search along top.
    for x in range(1, image.size[0] - 1):
        if image.getpixel((x, 1)) == colors['white']:
            return x, 1

    # Search along left side.
    for y in range(1, image.size[1] - 1):
        if image.getpixel((1, y)) == colors['white']:
            return 1, y

    # Maze is invalid if there is no entry point.
    raise Exception('No entry point found!')


def getExitPoint(image):
    # Search along bottom.
    for x in range(1, image.size[0] - 1):
        if image.getpixel((x, image.size[1] - 2)) == colors['white']:
            return x, image.size[1] - 2

    # Search along right side.
    for y in range(1, image.size[1] - 1):
        if image.getpixel((image.size[0] - 2, y)) == colors['white']:
            return image.size[0] - 2, y

    # Maze is invalid if there is no exit point.
    raise Exception('No exit point found!')


def solveRecursiveMaze(image, x, y):
    successful = False
    if (x, y) == getExitPoint(image):
        successful = True
    elif isValid(image, x, y):
        # set to show it's a visited path
        image.putpixel((x, y), colors['red'])

        successful = solveRecursiveMaze(image, x-1, y)    
        if not successful:
            successful = solveRecursiveMaze(image, x, y+1)
        if not successful:
            successful = solveRecursiveMaze(image, x+1, y)
        if not successful:
            successful = solveRecursiveMaze(image, x, y-1)

    if successful:
        # Mark to show it's a valid path.
        image.putpixel((x, y), colors['green'])

    return successful


def main(options):
    solved = False

    if options.depth:
        sys.setrecursionlimit(options.depth)

    try:
        image = PIL.Image.open(options.filename)
    except:
        print('ERROR: Could not open %s' % (options.filename))
    else:
        image = image.convert('RGB')

        x, y = getEntryPoint(image)
        print('Entering maze at x = %d, y = %d' % (x, y))
        solved = solveRecursiveMaze(image, x, y)
        if not solved:
            print('No solution exists.')
        else:
            print('Solved maze.')
            basename = os.path.splitext(options.filename)[0]
            image.save(basename + '_solution' + '.png', 'PNG')

    return 0 if solved else 1


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--d',
        '-depth',
        dest='depth',
        type=int,
        help='Set Python recursion limit with sys.setrecursionlimit()')
    parser.add_argument(
        'filename',
        help='Image containing the maze.')
    options = parser.parse_args()
    sys.exit(main(options))