运行 bfs 算法代码在 Python 时出现 TypeError
TypeError while running bfs algo code in Python
所以,这是我 运行 的代码,它给了我一个 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)
这是我遇到的错误:
路径=Grid.main(*Grid.get_start_cordinates())
TypeError:get_start_cordinates() 缺少 1 个必需的位置参数:'self'
path = maze.main(*maze.get_start_cordinates())
使用您创建的对象而不是 class。
所以,这是我 运行 的代码,它给了我一个 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)
这是我遇到的错误:
路径=Grid.main(*Grid.get_start_cordinates())
TypeError:get_start_cordinates() 缺少 1 个必需的位置参数:'self'
path = maze.main(*maze.get_start_cordinates())
使用您创建的对象而不是 class。