我正在尝试编写一个Python函数,它存储网格上两点之间的所有路径。 Here是最初的问题,我受到答案的启发,并试图在Python中创建一个类似的版本。
我能够成功打印出通过应用递归函数找到的所有路径,但问题是当我需要将它们存储在列表中时,我得到了一个空列表列表。我已经尝试使用全局变量和局部变量作为存储列表,并且它们给出了相同的结果。有谁可以请评论下面我的代码,并建议我做错了什么?
非常感谢!
import numpy as np
#initialize a matrix
grid = np.arange(0, 1225).reshape((35,35))
m = 10
n = 5
#starting point
s = (0, 0)
#target point
d = (n, m)
results = []
#a function to find the next step in the path
def next_step(x, y):
step = []
dx = [0, 1]
dy = [1, 0]
for i in range(2):
next_x = x + dx[i]
next_y = y + dy[i]
if next_x >= 0 and next_x <= n and next_y >= 0 and next_y <= m:
step.append((next_x, next_y))
return step
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
print(path)
else:
for step in next_step(s[0], s[1]):
if visited[step[0],step[1]] == False:
print_all_path(step, d, visited, path)
path.pop()
visited[s[0]][s[1]] = False
def print_path(s, d):
visited = np.zeros((35,35), dtype = bool)
path = []
print_all_path(s, d, visited, path)
print_path(s, d)
答案 0 :(得分:0)
问题可能是当你追加时,你只追加path
我怀疑你做了这样的事情:
# global
all_lists = []
# your functions
...
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
print(path)
all_lists.append(path)
...
但是,路径仍然与原始path
变量相关联。
您可以使用以下方法解决此问题:
all_lists.append(path + [])
这会复制列表并删除链接
所以整个程序现在是
import numpy as np
#initialize a matrix
grid = np.arange(0, 1225).reshape((35,35))
m = 10
n = 5
#starting point
s = (0, 0)
#target point
d = (n, m)
results = []
all_paths = []
#a function to find the next step in the path
def next_step(x, y):
step = []
dx = [0, 1]
dy = [1, 0]
for i in range(2):
next_x = x + dx[i]
next_y = y + dy[i]
if next_x >= 0 and next_x <= n and next_y >= 0 and next_y <= m:
step.append((next_x, next_y))
return step
def print_all_path(s, d, visited, path):
global results
visited[s[0]][s[1]] = True
path.append(grid[s[0]][s[1]])
if s == d:
results.append(path)
all_paths.append(path + [])
#print(path)
else:
for step in next_step(s[0], s[1]):
if visited[step[0],step[1]] == False:
print_all_path(step, d, visited, path)
path.pop()
visited[s[0]][s[1]] = False
def print_path(s, d):
visited = np.zeros((35,35), dtype = bool)
path = []
print_all_path(s, d, visited, path)
print_path(s, d)
print all_paths