如何只输出迷宫路径的转折点

How to only output turning points of a path for maze

所以我有一个 astar 算法可以输出迷宫中的路径。但我只想要你在迷宫中实际转弯的节点(表示为元组(行,列))。

例如。

path = [(10,0),(10,1),(9,1),(8,1),(8,2),(8,3),(7,3)] #given from astar alg  
path = [(10,0),(10,1),(8,1),(8,3),(7,3)] #desired output  

这是我的部分代码:

for node in self.path:
            direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
            direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1])
            if direction1 == direction2:
                self.path.pop([node+1])
            elif direction1 == None:
                pass
            else:
                pass

迭代self.path的索引使用:

for node in range(len(self.path)):

但由于您想在结束前停止检查 2(这样 self.path[node+2] 将始终有效)只需使用:

for node in range(0,len(self.path)-2):

无论哪种方式,在迭代路径时删除路径元素都可能会导致问题,因此我建议构建新路径然后替换旧路径:

new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(0,len(self.path)-2):
    direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
    direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1])
    if direction1 != direction2:
        new_path.append(self.path[node+1])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path

但这可能更令人困惑,因为你必须处理 node+1 然后 node 所以你可能想从索引 1 开始并在 len(self.path)-1 结束所以你会使用:

new_path = [self.path[0]] #keep the first element since it will always be needed
for node in range(1,len(self.path)-1):
    direction1 = (self.path[node-1][0] - self.path[node][0], self.path[node-1][1] - self.path[node][1])
    direction2 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1])
    if direction1 != direction2:
        new_path.append(self.path[node])
new_path.append(self.path[-1]) #add in the last element
self.path = new_path