Search code examples
pythonsearcha-star

a* search. adding movement cost from initial position


if f = g + h then where in the below code would I add g?

Also, besides adding the movement cost from my initial position, how else can I make this code more efficient?

def a_star(initial_node):
    open_set, closed_set = dict(), list()
    open_set[initial_node] = heuristic(initial_node)
    while open_set:
        onode = get_next_best_node(open_set)
        if onode == GOAL_STATE:
            return reconstruct_path(onode)
        del open_set[onode]
        closed_set.append(onode)
        for snode in get_successor_nodes(onode):
            if snode in closed_set:
                continue
            if snode not in open_set:
                open_set[snode] = heuristic(snode)
                self.node_rel[snode] = onode
    return False

Solution

  • In the last if, if snode is not in open_set (no pun intended!) you shouldn't set just the heuristic, but the heuristic plus the cost of the current node. And if snode is in the open set, you should check the minimum between the present value and the current one (if there are two or more ways to reach the same node, the least costly one should be considered).

    That means you need to store both the node's "actual" cost and the "estimated" cost. The actual cost of the initial node is zero. For every new node, it's the minimum for every incoming arc between the cost of the other vertex plus the cost of the arc (in other words, the cost of the last node plus the cost to move from that to the current one). The estimated cost would have to sum both values: the actual cost so far plus the heuristic function.

    I don't know how the nodes are represented in your code, so I can't give advice more specific than that. If you still have doubt, please edit your question providing more details.