【发布时间】:2019-09-24 10:36:45
【问题描述】:
所以,这是我正在运行的代码,它给了我一个 TypeError。我正在尝试遍历一个二维数组,然后返回从起点到目标点的路径。
我对路径遍历应用了广度优先搜索,但算法似乎有问题。
class Grid:
def __init__(self, str1):
self.maze = str1.splitlines()
def get_start_cordinates(self):
rr = 0
cc = 0
return rr, cc
def main(self, r, c):
queue = []
visited = {}
visited[(r, c)] = (-1, -1)
queue.append((r, c))
while len(queue) > 0:
r, c = queue.pop(0)
if r == 4 and c == 2:
path_actual = []
while r != -1:
path_actual.append((r, c))
r, c = visited[(r, c)]
path_actual.reverse()
return path_actual
# avoid repetition of code: make a loop
for dx, dy in ((-1, 0), (0, -1), (1, 0), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)):
new_r = r + dy
new_c = c + dx
if (0 <= new_r < len(self.maze) and
0 <= new_c < len(self.maze[0]) and
not (new_r, new_c) in visited):
visited[(new_r, new_c)] = (r, c)
queue.append((new_r, new_c))
maze = Grid("""1 12 2 0 0
2 11 1 11 0
3 2 -1 9 0""")
path = Grid.main(*Grid.get_start_cordinates())
print(path)
这是我得到的错误:
path = Grid.main(*Grid.get_start_cordinates())
TypeError: get_start_cordinates() 缺少 1 个必需的位置参数:'self'
【问题讨论】:
-
代替
Grid.main(...)调用maze.main(...) -
@kuco23 非常感谢。另外,请您检查此代码是否正确?因为我没有得到想要的输出。
-
你的逻辑似乎有缺陷。尝试空运行它,看看哪里出错了。
-
@NaumanNaeem 好的。谢谢您的帮助。在我自己检查整个算法后会更新这个问题,因为它只是给我输出“无”。再次感谢。
-
@Sanya 我在这里发现了一些问题。首先,当在字符串上调用
len时,它会给你字符串的长度,而你想要里面的元素数量。我认为在__init__内部应该是self.maze = [s.split() for s in str1.splitlines()],并且您颠倒了c 和r 的角色。 r 应该是行数,当你增加dy时,c 应该是列数,所以只需写if r == 2 and c == 4
标签: python search matrix breadth-first-search grid-search