how to find the best three routes using A* algorithm

后端 未结 1 564
予麋鹿
予麋鹿 2021-01-19 01:02

In A* usually the result that you get is only one path. Is it possible though for a given origin and destination to have 3 recommended path according to A*? So the second re

1条回答
  •  梦毁少年i
    2021-01-19 01:54

    This can be done quite easily if your language has support for backtracking/generators/iterators/coroutines.

    # Python code
    def astar(start):
        q = [start]    # priority queue
        while len(q) > 0:
            node = heappop(q)
            if isGoal(node):
                yield node
            for x in successors(node):
                heappush(q, x)
    

    The yield keyword is similar to return, except that the function may be re-entered after a yield to get the next solution. To get the best three:

    solutions = []
    i = 0
    for sol in astar(start):
        solutions.append(sol)
        if i == 3:
            break
        i += 1
    

    However, this will not work if you use a closed set (i.e., Russell & Norvig's graph search algorithm), since then part of the non-optimal solutions may be "cut off" when searching for the optimal one.

    0 讨论(0)
提交回复
热议问题