迭代时Python中的迷宫问题


map=  [[0, 1, 1, 1, 1, 1],
[ 0, 0, 1, 0, 0, 1],
[ 1, 0, 0, 0, 0, 1],
[ 1, 0, 1, 0, 1, 1],
[ 1, 0, 1, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1]]
class Runner:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def trans_loc(self, way):
if way =='left':
self.x += 1
elif way =='right':
self.x -= 1
elif way =='up':
self.y += 1
elif way =='down':
self.y -= 1
pass
def get_location(self): 
return (self.x, self.y)
class Labyrinth:
def __init__(self, map=None):
self.map = map
self.player = Runner()
self.road = []
def running(self): # Problem is Here
x,y = self.player.get_location()
self.road.append((x,y))
lim = len(map)-1

while lim:
x += 1
y += 1
self.road.append((x,y))

if x == lim and y == lim:
break
def given_map(self):
return self.map
def path_find(self):
return self.road
if __name__ == "__main__" :
trial = Labyrinth(map)
trial.running()
print(trial.given_map())
print(trial.path_find())

老实说,该代码是myschool项目的一部分。经过长时间的谷歌搜索和思考,我只能在这里完成它。代码的操作方法设计如下。获取迷宫地图列表。然后只返回零的零件,并将其添加到self.load中。我的问题是,我不知道如何编织run((函数部分和trans_loc((分。我知道这个网站最初并不是为了这个目的发布问题的,但我无法忍受,因为我自己太可怜了。说一些苦涩的话是可以的,所以如果你能给我一个间接的解决方案,我真的很感激。

如果你只想要矩阵中所有位置的坐标值为0,那么你可以这样做:

lab =   [[0, 1, 1, 1, 1, 1],
[ 0, 0, 1, 0, 0, 1],
[ 1, 0, 0, 0, 0, 1],
[ 1, 0, 1, 0, 1, 1],
[ 1, 0, 1, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1]]
zeros = [(x,y) for y,l in enumerate(lab) for x,e in enumerate(l) if e == 0]
print(zeros)

如果你想要最短的路径,你可以使用像这样的递归

def getv(x, l): return x if x in range(len(l)) else -1
def move(x, y, lab):
# Set current place to 1 to avoid going back
lab[y][x] = 1 
# Check if we are in the goal
if x == len(lab[y])-1: return [(x,y)]
# Check if we are out of bounds 
if x < 0 or y < 0: return None
up = right = left = down = None
# Recursively check all paths
if lab[getv(y+1,lab)][x]    == 0: down    = move(x,y+1, lab)
if lab[getv(y-1,lab)][x]    == 0: up      = move(x,y-1, lab)
if lab[y][getv(x+1,lab[y])] == 0: left    = move(x+1,y, lab)
if lab[y][getv(x-1,lab[y])] == 0: right   = move(x-1,y, lab)
# Only return coordinates of valid paths
if   up:    return [(x,y)] + up
elif down:  return [(x,y)] + down
elif left:  return [(x,y)] + left
elif right: return [(x,y)] + right 
def draw(path, lab):
for x,y in path: lab[y][x] = '+'
for x in lab: print(' '.join(str(x) for x in x))
# Find the path on the lab
path = move(0,0, 
[[0, 1, 1, 1, 1, 1],
[ 0, 0, 1, 0, 0, 1],
[ 1, 0, 0, 0, 0, 1],
[ 1, 0, 1, 0, 1, 1],
[ 1, 0, 1, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1]])

# path is [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (3, 2), (3, 3), (3, 4), (4, 4), (5, 4)]

# Draw the path on the lab
draw(path,
[[0, 1, 1, 1, 1, 1],
[ 0, 0, 1, 0, 0, 1],
[ 1, 0, 0, 0, 0, 1],
[ 1, 0, 1, 0, 1, 1],
[ 1, 0, 1, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1]])

打印

+ 1 1 1 1 1
+ + 1 0 0 1
1 + + + 0 1
1 0 1 + 1 1
1 0 1 + + +
1 1 1 1 1 1

最新更新