python迷宫递归没有递归

时间:2013-11-04 01:05:59

标签: python recursion maze

我正在尝试递归地解决迷宫,我可以让它去我想要的地方(检查以确保它可以采取一种方式,然后将其标记为已存在)但出于某种原因,当它运行时进入一个死胡同,它不会递归地回到一个空旷的地方检查另一条路径。我使用递归的方式有什么问题吗?

class maze(object):
    def __init__(self, maze):
        self.maze = maze
        self.maze2d = []
        n = 0
        i = 0
        for row in self.maze:
            self.maze2d.append([])
            print(row)
            for col in row:
                self.maze2d[i].append(col)
            i += 1
        print(self.maze2d)

    def find_start(self):
        x = 0 
        y = 0
        for row in self.maze2d:
            for index in row:
                if index == "S":
                    self.maze2d[x][y] = index
                    return x,y
                y += 1
            x += 1
            y = 0
        return -1

    def mazeSolver(self,x,y,path):
        if self.maze2d[x][y] == "E":
            return True
        else:
            if self.maze2d[x] != 0: 
                if self.maze2d[x+1][y] == ".":
                    self.maze2d[x+1][y] = "_"
                    self.mazeSolver(x+1,y,path + "S")
            if self.maze2d[x] < len(self.maze2d):
                if self.maze2d[x-1][y] == ".":
                    self.maze2d[x-1][y] = "_"
                    self.mazeSolver(x-1,y,path + "N")
            if y < len(self.maze2d[x]): 
                if self.maze2d[x][y+1] == ".":
                    self.maze2d[x][y+1] = "_"
                    self.mazeSolver(x,y+1,path + "E")
            if self.maze2d[y] != 0:
                if self.maze2d[x][y-y] == ".":
                    self.maze2d[x][y-1] = "_"
                    self.mazeSolver(x,y-1,path + "W")

我正在调用函数和迷宫本身:

from eachstep import *

maze1 = []

maze1.append("S..*..")
maze1.append("*...*.")
maze1.append("..*..E")

var1 = maze(maze1)
x,y = var1.find_start()
var1.mazeSolver(x,y,"")

2 个答案:

答案 0 :(得分:1)

我用这个改变了你的mazeSolver功能。我在最后打印路径:

def mazeSolver(self,x,y,path):
    if self.maze2d[x][y] == '.':
        self.maze2d[x][y] = "_"
    if self.maze2d[x][y] == "E":
        print path
        return True
    else:
        if x < len(self.maze2d)-1: 
            if self.maze2d[x+1][y] in ['.','E']:
                self.mazeSolver(x+1,y,path + "S")
        if x > 0:
            if self.maze2d[x-1][y]  in ['.','E']:
                self.mazeSolver(x-1,y,path + "N")
        if y < len(var1.maze2d[x])-1: 
            if self.maze2d[x][y+1]  in ['.','E']:
                self.mazeSolver(x,y+1,path + "E")
        if y > 0:
            if self.maze2d[x][y-y]  in ['.','E']:
                self.mazeSolver(x,y-1,path + "W")

>>> var1.mazeSolver(x,y,"")
ESEESEE
>>>> var1.maze2d
[['S', '_', '_', '*', '.', '.'],
 ['*', '_', '_', '_', '*', '.'],
 ['_', '_', '*', '_', '_', 'E']]

答案 1 :(得分:0)

您的代码永远不会到达目的地,因为它只访问值为.的地理位置,结尾的值为E