Python 如果存在';没有路

Python 如果存在';没有路,python,algorithm,search,artificial-intelligence,a-star,Python,Algorithm,Search,Artificial Intelligence,A Star,我找到了这个算法,但似乎创建者没有测试是否存在没有路径的情况。如果没有路径,而且我不知道解决方案,那么开放列表的长度似乎会越来越大。这是我的第一篇帖子,对于我犯的任何错误,我深表歉意,非常感谢你的帮助 class Node(): """A node class for A* Pathfinding""" def __init__(self, parent=None, position=None): self.parent = parent sel

我找到了这个算法,但似乎创建者没有测试是否存在没有路径的情况。如果没有路径,而且我不知道解决方案,那么开放列表的长度似乎会越来越大。这是我的第一篇帖子,对于我犯的任何错误,我深表歉意,非常感谢你的帮助

class Node():
    """A node class for A* Pathfinding"""

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.g = 0
        self.h = 0
        self.f = 0

    def __eq__(self, other):
        return self.position == other.position


def astar(maze, start, end):
    """Returns a list of tuples as a path from the given start to the given end in the given maze"""

    # Create start and end node
    start_node = Node(None, start)
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, end)
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both open and closed list
    open_list = []
    closed_list = []

    # Add the start node
    open_list.append(start_node)

    # Loop until you find the end
    while len(open_list) > 0:

        # Get the current node
        current_node = open_list[0]
        current_index = 0
        for index, item in enumerate(open_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index

        # Pop current off open list, add to closed list
        open_list.pop(current_index)
        closed_list.append(current_node)

        # Found the goal
        if current_node == end_node:
            path = []
            current = current_node
            while current is not None:
                path.append(current.position)
                current = current.parent
            return path[::-1] # Return reversed path

        # Generate children
        children = []
        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares

            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

            # Make sure within range
            if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
                continue

            # Make sure walkable terrain
            if maze[node_position[0]][node_position[1]] != 0:
                continue

            # Create new node
            new_node = Node(current_node, node_position)

            # Append
            children.append(new_node)

        # Loop through children
        for child in children:

            # Child is on the closed list
            for closed_child in closed_list:
                if child == closed_child:
                    continue

            # Create the f, g, and h values
            child.g = current_node.g + 1
            child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)
            child.f = child.g + child.h

            # Child is already in the open list
            for open_node in open_list:
                if child == open_node and child.g > open_node.g:
                    continue

            # Add the child to the open list
            open_list.append(child)


def main():

    maze = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]

    start = (0, 0)
    end = (7, 6)

    path = astar(maze, start, end)
    return path

print(main())
class节点():
“”“用于*寻路的节点类”“”
定义初始化(self,parent=None,position=None):
self.parent=parent
self.position=位置
self.g=0
self.h=0
self.f=0
定义(自身、其他):
返回self.position==其他.position
def astar(迷宫、开始、结束):
“”“返回元组列表,作为给定迷宫中从给定起点到给定终点的路径”“”
#创建开始和结束节点
开始\节点=节点(无,开始)
开始节点。g=开始节点。h=开始节点。f=0
结束\节点=节点(无,结束)
end_node.g=end_node.h=end_node.f=0
#初始化打开和关闭列表
打开列表=[]
已关闭的_列表=[]
#添加开始节点
打开\u列表。追加(开始\u节点)
#循环直到找到终点
而len(开放列表)>0:
#获取当前节点
当前\u节点=打开\u列表[0]
当前指数=0
对于索引,枚举中的项(打开列表):
如果.f项<当前节点.f:
当前节点=项目
当前索引=索引
#弹出当前关闭打开列表,添加到关闭列表
打开\u列表.pop(当前\u索引)
关闭\u列表。追加(当前\u节点)
#找到目标
如果当前_节点==结束_节点:
路径=[]
当前=当前节点
虽然当前值不是“无”:
path.append(当前位置)
current=current.parent
返回路径[:-1]#返回反向路径
#生子
儿童=[]
对于[(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(-1,1),(1,1)]中的新_位置:
#获取节点位置
节点位置=(当前节点位置[0]+新位置[0],当前节点位置[1]+新位置[1])
#确保在范围内
如果节点位置[0]>(len(迷宫)-1)或节点位置[0]<0或节点位置[1]>(len(迷宫)[len(迷宫)-1])-1)或节点位置[1]<0:
持续
#确保可行走的地形
如果迷宫[节点位置[0]][节点位置[1]!=0:
持续
#创建新节点
新节点=节点(当前节点,节点位置)
#附加
附加(新的_节点)
#环游儿童
对于儿童中的儿童:
#孩子在关闭名单上
对于已关闭\u列表中的已关闭\u子项:
如果子项==关闭的子项:
持续
#创建f、g和h值
child.g=当前_节点.g+1
child.h=((child.position[0]-end_node.position[0])**2+((child.position[1]-end_node.position[1])**2)
child.f=child.g+child.h
#子项已在打开列表中
对于“打开”列表中的“打开”节点:
如果child==open_node和child.g>open_node.g:
持续
#将子项添加到打开列表中
打开\u列表。追加(子项)
def main():
迷宫=[[0,0,0,0,1,0,0,0,0,0,0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]
开始=(0,0)
结束=(7,6)
路径=astar(迷宫、开始、结束)
返回路径
打印(main())

关闭的\u列表
应该是
集合
,而不是
列表
,以检查是否已访问
节点
。这允许移除检查节点是否被访问的内部循环,并非常有效地执行此操作
但这不仅仅是一种优化:它允许
continue
在外循环结束时,在应该继续执行的地方继续执行。这是代码中的主要错误:
continue
只在内部循环结束时使用,本质上使已访问的检查无效:您不断地重复添加相同的节点,不管它们是否已被访问

为了在
集合中具有
节点
节点
必须是可散列的。这里,我返回元组
位置的哈希值

修改后的代码返回路径(如果存在),或者不返回路径

class Node():
    """A node class for A* Pathfinding"""

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.g = 0
        self.h = 0
        self.f = 0

    def __eq__(self, other):
        return self.position == other.position

    def __hash__(self):               #<-- added a hash method
        return hash(self.position)


def astar(maze, start, end):
    """Returns a list of tuples as a path from the given start to the given end in the given maze"""

    # Create start and end node
    start_node = Node(None, start)
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, end)
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both open and closed list
    open_list = []
    closed_list = set()                # <-- closed_list must be a set

    # Add the start node
    open_list.append(start_node)

    # Loop until you find the end
    while len(open_list) > 0:

        # Get the current node
        current_node = open_list[0]
        current_index = 0
        for index, item in enumerate(open_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index

        # Pop current off open list, add to closed list
        open_list.pop(current_index)
        closed_list.add(current_node)     # <-- change append to add

        # Found the goal
        if current_node == end_node:
            path = []
            current = current_node
            while current is not None:
                path.append(current.position)
                current = current.parent
            return path[::-1] # Return reversed path

        # Generate children
        children = []
        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares

            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

            # Make sure within range
            if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
                continue

            # Make sure walkable terrain
            if maze[node_position[0]][node_position[1]] != 0:
                continue

            # Create new node
            new_node = Node(current_node, node_position)

            # Append
            children.append(new_node)

        # Loop through children
        for child in children:

            # Child is on the closed list
            if child in closed_list:              # <-- remove inner loop so continue takes you to the end of the outer loop
                continue

            # Create the f, g, and h values
            child.g = current_node.g + 1
            child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)
            child.f = child.g + child.h

            # Child is already in the open list
            for open_node in open_list:
                if child == open_node and child.g > open_node.g:
                    continue

            # Add the child to the open list
            open_list.append(child)


def main():

    maze = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]

    start = (0, 0)
    end = (7, 6)

    path = astar(maze, start, end)
    return path

print(main())
class节点():
“”“用于*寻路的节点类”“”
定义初始化(self,parent=None,position=None):
self.parent=parent
self.position=位置
self.g=0
self.h=0
self.f=0
定义(自身、其他):
返回self.position==其他.position
定义散列(self):(len(迷宫[len(迷宫)-1])-1)或节点位置[1]<0:
持续
#确保可行走的地形
如果迷宫[节点位置[0]][节点位置[1]!=0:
持续
#创建新节点
新节点=节点(当前节点,节点位置)
#附加
附加(新的_节点)
#环游儿童
对于儿童中的儿童:
#孩子在关闭名单上
如果子节点位于关闭的节点列表中:#打开节点.g:
持续
#将子项添加到打开列表中
打开\u列表。追加(子项)
def main():
迷宫=[[0,0,0,0,1,0,0,0,0,0,0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],