[英]How to come to the ending point of a maze?
在read_file方法中的代碼中,我正在讀取文件並返回包含迷宮行的2d數組。 例如[[1 0 0 0 0 1 0 0],[0 0 0 1 0 0 1 0 0]]
2是迷宮的起點,而3是迷宮的終點。
import numpy as np
class Maze:
@staticmethod
def read_file(file):
""" function that reads the file and returns the content of the file in an array """
# dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=int)
# add lines to array
for index, line in enumerate(lines):
for i in range(0, len(line) - 1):
# replace line content with the ones from the dictionary and add it to the array
maze_array[index][i] = replacements.get(line[i], line[i])
return maze_array
現在,我想穿過迷宮並從起點開始到達終點。 為此,我編寫了一種稱為search的方法。 在這種方法中,我檢查迷宮的細胞。 當一個單元等於3時,我發現迷宮的盡頭。 等於0是一堵牆,等於1是一個我可以通過的空單元格。 經過單元格后,我將它們設置為4以將其標記為已訪問。 然后在下面遞歸調用。
@staticmethod
def search(x, y, array):
"""
0: wall
1: empty
2: starting point
3: ending point
4: visited cell
"""
if array[x][y] == 3:
print('end at %d,%d' % (x, y))
return True
elif array[x][y] == 0:
print('wall at %d,%d' % (x, y))
return False
elif array[x][y] == 4:
print('visited at %d,%d' % (x, y))
return False
print('visiting %d,%d' % (x, y))
array[x][y] == 4
if ((x < len(array) - 1 and Maze.search(x + 1, y, array))
or (y > 0 and Maze.search(x, y - 1, array))
or (x > 0 and Maze.search(x - 1, y, array))
or (y < len(array) - 1 and Maze.search(x, y + 1, array))):
return True
return False
def main():
""" Launcher """
# [1][1] is starting point
array = Maze.read_file("maze-one.txt")
Maze.search(1, 1, array)
if __name__ == "__main__":
main()
沒用 我已經通過@Florian H更改了代碼,但是仍然出現以下錯誤:
RecursionError: maximum recursion depth exceeded while calling a Python object
但是我需要遍歷整個迷宮才能得出終點。 遞歸調用有可能嗎?還是太多了? 除了使用遞歸調用,還有其他解決方案嗎?
您可以通過以下方式在遞歸函數中重新加載文件:
array = Maze.read_file('maze-one.txt')
在每個遞歸步驟中,因此array[x][y] == 4
每次都會被重載覆蓋。 這意味着您的迷宮總是不被訪問,並且您的遞歸是無限的。
編輯您的評論
我並不是說您應該使用全局變量,但這是一個選擇。 在您的情況下,我更喜歡一個函數參數。
首先,您既不需要靜態方法中的self
參數,也不需要僅具有靜態元素的類的對象,但這就是一個不同的主題,在這里要進行很多說明。 您可能會自己了解OOP。
您可以將迷宮作為函數參數,如下所示:
def search(x, y, array):
...
比您從主要方法調用它的方式更像:
def main():
""" Launcher """
# [1][1] is starting point
Maze.search(1, 1, Maze.load_file('maze-one.txt'))
從search
功能中刪除Maze.search
行,並以相同的方式更改搜索方法中的Maze.search
函數調用。
if ((x < len(array) - 1 and Maze.search(x + 1, y, array))...
第二次編輯
我並沒有真正獲得您的搜索功能的if部分。 但是本能地將其拆分為單個,如果類似於以下內容:
if x < len(array) -1:
if Maze.search(x + 1, y, array):
return True
if y > 0:
if Maze.search(x, y - 1, array):
return True
if x > 0:
if Maze.search(x - 1, y, array):
return True
if y < len(array):
Maze.search(x, y + 1, array):
return True
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.