You need to enable JavaScript to run this app. Python实现A*搜索算法时回溯仅生效一次、无法遍历未探索节点的问题
优惠活动
大模型
产品
解决方案
定价
更多

Python实现A*搜索算法时回溯仅生效一次、无法遍历未探索节点的问题

A*算法回溯逻辑异常问题说明

问题场景

我是Python入门开发者,正在实现A*搜索算法,目前在搜索回溯、未访问节点探索环节遇到异常:回溯逻辑仅能单次执行,无法持续遍历所有未访问的邻居节点。

实际遍历表现

当前算法跑通后的节点访问顺序(含各节点的邻居列表)如下:

  • 节点1(邻居:2、12、1363)→ 节点2(邻居:1、13、48)→ 节点13(邻居:2)
  • 节点2(邻居:1、13、48)→ 节点48(邻居:2)
    从结果可以发现,算法从未探索节点1的其余邻居(12、1363),但遍历了节点2的其他邻居,目前无法定位异常根因。

疑似问题代码片段

def distance(startnode, endnode, graphone):
    """计算两个顶点之间的距离"""
    startNeighbors = startnode.getNeighbors(graphone)
    startWeights = startnode.getWeights()
    startWeights.sort()
    index = startWeights.index(min(startWeights))
    dist.add(startWeights[index])
    endIndex = endnode.index
    path.add(startnode.index)
    startNeighborsIndex = []
    for number in startNeighbors:
        startNeighborsIndex.append(number.index)
    
    if endIndex in startNeighborsIndex: 
        return path.add(endnode.index)
    elif startNeighborsIndex[index] in path and len(startNeighborsIndex) > 1: # 回溯逻辑
        i = 0
        for item in startNeighborsIndex:
            if item not in path:
                return distance(graphone.getVertex(startNeighborsIndex[i]),endnode,graphone)
            i = i + 1
        # 以下为尝试过但未生效的回溯分支逻辑
        # if index + 1 < len(startNeighbors)-1:
        #     return distance(graph.getVertex(startNeighbors[index+1]),n2,graph)
        # elif index + 1 == len(startNeighbors):
        #     return distance(graph.getVertex(startNeighbors[index]),n2,graph)
        # elif index + 1 > len(startNeighbors)-1:
        #     return distance(graph.getVertex(startNeighbors[index-1]),n2,graph)
        # else:
        #     return distance(graph.getVertex(startNeighbors[len(startNeighbors)-1]),n2,graph)
        
    else: 
        return distance(graphone.getVertex(startNeighborsIndex[index]),endnode,graphone)

完整实现代码

from abc import ABCMeta, abstractmethod
from heapq import heappush, heappop, heapify
import fileinput
import math

Infinite = float('inf')
dist = set()
path = set()

def __main__():
    graphone = readGraph('data/USA-road-d.NY.gr')
    co = readCoordinates('data/USA-road-d.NY.co')
    startNode = graphone.getVertex(1)
    endNode = graphone.getVertex(3)
    costFunc = distance(startNode,endNode,graphone)
    # find_path(startNode,endNode,neighbors_fnct=startNode.neighbors(graphone),heuristic_cost_estimate_fnct=distance(startNode,endNode,graphone),distance_between_fnct=distance(startNode,endNode,graphone))
    find_path(startNode,endNode,neighbors_fnct=startNode.neighbors(graphone),heuristic_cost_estimate_fnct=distance(graphone),distance_between_fnct=distance(graphone))
    
def readGraph(filePath):
    n_vertices = 0
    for line in fileinput.input([filePath]):
        words = line.split(" ")
        if (words[0] == "p"):
            n_vertices = int(words[2])
    graph = Graph(n_vertices)
    for line in fileinput.input([filePath]):
        words = line.split(" ")
        if (words[0] == "a"):
            graph._addVertex(int(words[1]), int(words[2]), float(words[3]))
    return graph


# 读取坐标数据
def readCoordinates(filepath):
    # 节点索引从1开始计数
    coordinates = [None]
    for line in fileinput.input([filepath]):
        words = line.split(" ")
        if (words[0] == "v"):
            coordinates.append([float(words[2]), float(words[3])])
    return coordinates

class Vertex:
    # 顶点初始化,绑定关联邻居与对应权重
    # 每个顶点维护自身的邻居列表与对应权重列表
    def __init__(self, i, neighbor_index, weight):
        self.index = i
        self.neighbors = [neighbor_index]
        self.weights = [weight]
        
    def getNeighbors(self,graphone):
        neighborList = self.neighbors
        neighbors = []
        for number in neighborList:
            neighbors.append(graphone.getVertex(number))
        return neighbors
    
    def getWeights(self):
        return self.weights
    
    # 为顶点新增带对应权重的邻居关系
    def _addNeighbor(self, neighbor_index, weight):
        self.neighbors.append(neighbor_index)
        self.weights.append(weight)


# 图数据结构
class Graph:
    # 初始化含n_vertices个节点的图
    # 图内部维护顶点列表
    def __init__(self, n_vertices):
        self.vertices = [None] * (n_vertices+1)
        self.num_vertices = n_vertices
    
    # 获取索引为i的节点
    def getVertex(self, i): # 递归深度报错点
        if ((i > self.num_vertices) | (i <= 0)):
            raise ValueError(f'index {i} is out of bounds')
        else:
            return self.vertices[i]
    
    # 向图中新增顶点
    def _addVertex(self, vertex_index, neighor_index, distance):
        if (self.vertices[vertex_index] == None):
            # 新建顶点
            self.vertices[vertex_index] = Vertex(vertex_index, neighor_index, distance)
        else:
            # 顶点已存在,补充新增边关联
            self.vertices[vertex_index]._addNeighbor(neighor_index, distance)

    def getTrueDistance(self,startNode, endNode):
        startIndex = startNode.index
        endIndex = endNode.index

def distance(startnode, endnode, graphone):
    """计算两个顶点之间的距离"""
    startNeighbors = startnode.getNeighbors(graphone)
    startWeights = startnode.getWeights()
    startWeights.sort()
    index = startWeights.index(min(startWeights))
    dist.add(startWeights[index])
    endIndex = endnode.index
    path.add(startnode.index)
    startNeighborsIndex = []
    for number in startNeighbors:
        startNeighborsIndex.append(number.index)
    
    if endIndex in startNeighborsIndex: 
        return path.add(endnode.index)
    elif startNeighborsIndex[index] in path and len(startNeighborsIndex) > 1: # 回溯逻辑
        i = 0
        for item in startNeighborsIndex:
            if item not in path:
                return distance(graphone.getVertex(startNeighborsIndex[i]),endnode,graphone)
            i = i + 1
        
    else: 
        return distance(graphone.getVertex(startNeighborsIndex[index]),endnode,graphone)
    

class AStar:
    __metaclass__ = ABCMeta
    __slots__ = ()

    class SearchNode:
        __slots__ = ('data', 'gscore', 'fscore',
                     'closed', 'came_from', 'out_openset')

        def __init__(self, data, gscore=Infinite, fscore=Infinite):
            self.data = data
            self.gscore = gscore
            self.fscore = fscore
            self.closed = False
            self.out_openset = True
            self.came_from = None

        def __lt__(self, b):
            return self.fscore < b.fscore

    class SearchNodeDict(dict):

        def __missing__(self, k):
            v = AStar.SearchNode(k)
            self.__setitem__(k, v)
            return v

    @abstractmethod
    def heuristic_cost_estimate(self, current, goal):
        """估算当前节点到目标节点的大致距离,该方法需在子类中实现,第二个参数固定为目标节点"""
        raise NotImplementedError

    @abstractmethod
    def distance_between(self, n1, n2):
        """返回两个相邻节点的真实距离(即n2属于n1的邻居列表),入参n2必然是n1调用neighbors方法返回的列表中的项,该方法需在子类中实现"""
        raise NotImplementedError

    @abstractmethod
    def neighbors(self, current):
        """返回给定节点的所有邻居列表,该方法需在子类中实现"""
        vertex = Vertex(node)
        raise NotImplementedError

    def is_goal_reached(self, current, goal):
        """判断当前节点是否已到达目标节点"""
        return current == goal

    def reconstruct_path(self, last, reversePath=False):
        def _gen():
            current = last
            while current:
                yield current.data
                current = current.came_from
        if reversePath:
            return _gen()
        else:
            return reversed(list(_gen()))

    def astar(self, start, goal, reversePath=False):
        if self.is_goal_reached(start, goal):
            return [start]
        searchNodes = AStar.SearchNodeDict()
        startNode = searchNodes[start] = AStar.SearchNode(
            start, gscore=.0, fscore=self.heuristic_cost_estimate(start,goal))
        openSet = []
        heappush(openSet, startNode)
        while openSet:
            current = heappop(openSet)
            if self.is_goal_reached(current.data, goal):
                return self.reconstruct_path(current, reversePath)
            current.out_openset = True
            current.closed = True
            for neighbor in map(lambda n: searchNodes[n], self.neighbors(current.data)):
                if neighbor.closed:
                    continue
                tentative_gscore = current.gscore + \
                    self.distance_between(current.data, neighbor.data)
                if tentative_gscore >= neighbor.gscore:
                    continue
                neighbor.came_from = current
                neighbor.gscore = tentative_gscore
                neighbor.fscore = tentative_gscore + \
                    self.heuristic_cost_estimate(neighbor.data, goal)
                if neighbor.out_openset:
                    neighbor.out_openset = False
                    heappush(openSet, neighbor)
                else:
                    heapify(openSet)
        return None


def find_path(start, goal, neighbors_fnct, reversePath=False, heuristic_cost_estimate_fnct=lambda a, b: Infinite, distance_between_fnct=lambda a, b: 1.0, is_goal_reached_fnct=lambda a, b: a == b):
    """非类实现版本的路径查找算法"""
    class FindPath(AStar):

        def heuristic_cost_estimate(self, current, goal):
            return heuristic_cost_estimate_fnct(current, goal)

        def distance_between(self, n1, n2):
            return distance_between_fnct(n1, n2)

        def neighbors(self, node):
            return neighbors_fnct(node)

        def is_goal_reached(self, current, goal):
            return is_goal_reached_fnct(current, goal)
    return FindPath().astar(start, goal, reversePath)

if __name__ == '__main__':
    __main__()

内容的提问来源于stack exchange,提问作者omarT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 17:24:04