Search code examples
path-finding

Will Dijkstra or A* work correctly with cost a function of full path?


What I'm considering is this: when a node becomes the current node, compute "on the fly" the cost to each neighbor, where the cost is a function of the complete path to arrive at the current node. I can't think how this would break the assumptions of the algorithm, but I have a feeling it might.

I'm doing the on the fly computation for storage reasons anyway, but the new thing would be having the costs be a function of more than the two nodes involved. Could it work?


Solution

  • As far as I see, it doesn't break the assumptions of the Dijsktra algorithm, i.e. you can still continue to use it. However, when you want to do so, it does require you to completely refigure your graph.

    More detailed, you can't simply use Node-Indices {1,...,N} anymore, but then your state rather needs to be something like {(1,all-ways-to-get-there), ... , (N,all-ways-to-get-there)}. This will bring in a bad exponential scaling.

    The reason for this is that the Dijkstra algorithm -- like Dynamic programming -- relies on the fact that the problem can be split in parts and solved there, which is not the case here.

    Here is an example why it can't be done by "normal" Dijkstra: say your function which assigns a cost to a given way {node_1, node_2, ..., node_N} is called f and is assumed arbitrary. Then it is completely irrelevant what your current best costs or best path {node_1, ..., node_{N-1}} is at the moment, as you can't make any implication on that -- all you can do is to work out each possible path, which grows exponentially and is hopeless for large graphs.

    In case your function fulfills some requirements, however, there might be better things to do. For example, in the simplest case when your function is linear, f({path1} + {path2}) = f({path1}) + f({path2})], the "original" Dijkstra algorithm is recovered.