【发布时间】:2020-12-24 13:00:15
【问题描述】:
我正在尝试编写一个程序,该程序接受一个矩阵,该矩阵表示一个充满 0 和 1 的板。 目标是使用回溯找到从左上角位置到目标位置的路径。您一次只能向上、向下、向左和向右移动一个空间。下面的代码引发了
RecursionError: maximum recursion depth exceeded in comparison
为什么会导致错误?有没有办法同时向上、向下、向右和向左移动而不会导致此错误?
class Maze:
def __init__(self, maze, target):
self.x, self.y = target
self.b = maze
self.n = len(self.b)
self.sb = [[0 for _ in range(self.n)] for _ in range(self.n)]
def is_safe(self, row, col):
if 0 <= row < self.n and 0 <= col < self.n and self.b[row][col] == 1:
return True
return False
def find_path(self):
move_x = [1, -1, 0, 0]
move_y = [0, 0, 1, -1]
if not self.find_path_rec(move_x, move_y, 0, 0):
print("No path")
else:
self.print_maze()
def find_path_rec(self, move_x, move_y, curr_x, curr_y):
if curr_y == self.y and curr_x == self.x and self.b[self.x][self.y] == 1:
self.sb[curr_x][curr_y] = 1
return True
for i in range(4):
new_x = move_x[i] + curr_x
new_y = move_y[i] + curr_y
if self.is_safe(new_x, new_y):
self.sb[new_x][new_y] = 1
if self.find_path_rec(move_x, move_y, new_x, new_y):
return True
self.sb[new_x][new_y] = 0
return False
def print_maze(self):
for i in range(self.n):
for j in range(self.n):
print(self.sb[i][j], end="")
print()
maze = [[1, 1, 1, 1],
[1, 1, 0, 1],
[1, 0, 0, 1],
[1, 1, 0, 1]]
【问题讨论】:
-
要了解递归,需要了解递归。对了,你查
self.sb吗?
标签: python recursion path-finding