3

我正在尝试递归地解决一个迷宫,我可以让它去我想要的地方(检查以确保它可以走一条路,然后将它标记为在那里)但是由于某种原因,当它遇到死机时最后,它不会递归地回到一个开放的地方来检查另一条路径。我使用递归的方式有什么问题吗?

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,"")
4

2 回答 2

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']]
于 2013-11-04T02:05:09.127 回答
0

您的代码永远不会到达末尾,因为它只访问具有 value 的位置.,而 end 具有 value E

于 2013-11-04T01:27:39.850 回答