【发布时间】:2015-04-05 07:32:41
【问题描述】:
我正在做一个项目来建造一个完美的迷宫。 我有一个 Maze 类和一个 Cell 类,它代表迷宫中的每个正方形。在我的单元格类中,我有四个布尔变量(北、南、东、西)来表示单元格的北边或南边是否有墙。还有一个名为 visit 的布尔变量,用于检查单元格是否已被访问。这是 Cell 类的 init() 代码。
def __init__(self):
self.north = True
self.south = True
self.east = True
self.west = True
self.visit = False
对于 Maze 类,我有 self.maze(一堆 Cell)和 self.size = N(构建一个 N*N 迷宫)。 这是 Maze 类的 init():
def __init__(self, N):
self.size = N
self.maze = [[i for i in range(N + 2)] for i in range(N + 2)]
for r in range(self.size + 2):
for c in range(self.size + 2):
self.maze[r][c] = Cell()
在更新迷宫索引时,我编写了两个函数来检查 newX 和 newY 是否在 1
def in_range(self, x, y):
if 1 <= x <= self.size and 1 <= y <= self.size:
return True
else:
return False
def is_valid(self, x, y):
if not self.maze[x][y].getVisit() and self.in_range(x,y):
return True
else:
return False
在这之后,我写了主要的结构:
def walk(self, s, x, y):
neighbor = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
if s.size() == self.size**2: return
else:
while True:
new = choice(neighbor)#choice() is import from random
#print(self.is_valid(new[0], new[1]))
if self.is_valid(new[0], new[1]):break
else:
if len(neighbor) != 0:
neighbor.remove(new)
new = choice(neighbor)
else:
temp = s.pop(s)
self.walk(s, temp[0], temp[1])
break
print(new)
但是,运行我的代码仍然给我的索引不在 1 和 self.size 之间。我不知道为什么,我认为我的检查算法工作正常。 这是我得到的:
>>> ================================ RESTART
================================
>>>
>>> a = Maze(5)
>>> a.search()
1 2
(1, 3)
(2, 3)
(2, 4)
(1, 4)
(2, 4)
(2, 5)
(3, 5)
(4, 5)
(4, 4)
(4, 3)
(3, 3)
(3, 2)
(2, 2)
(2, 1)
(1, 1)
(0, 1)
(-1, 1)
(0, 1)
(1, 1)
(0, 1)
(-1, 1)
(-1, 2)
(-1, 1)
(0, 1)
有人可以帮帮我吗? lz,真的很感激!
【问题讨论】:
-
又是build-a-perfect-maze一周吗?
-
你为什么到处使用
range(N + 2)?这将创建一个 (N+1)x(N+1) 迷宫。只需创建一个numpy.array 的 Cell。 -
很高兴为您提供帮助。能否请您发布您的迷宫和牢房的课程代码?
-
if s.size() == self.size**2: return在检查什么?那是怎样的终止条件?除非您尝试随机发现长度为 N**2 的路径(但它们不一定是循环或完全遍历)。 -
因为教授说要建立一个 N+2 迷宫以避免一些乏味的问题。老实说,我也不知道原因。
标签: python recursion path-finding maze