Find the shortest path while avoiding certain labelled nodes if possible

Hello! I have a situation where I need to route from point A-B, but avoiding nodes with a specific flag unless necessary

Take the following graph for example

Les assume B is flagged as avoided, and I want to navigate from A -> C

With this I would expect the shortest path to be A -> D -> E -> C

However if we change the graph and remove the nodes D and E, I would expect it to route A -> B -> C, even though B is avoided

Is something like this possible?

Thanks!

You can use the shortestPath() to find the shortest path, while applying your condition in a 'where' clause.

I don't really know how to do what you want in a single shortestPath() query, as you are asking the algorithm to change the criteria after it finds there is no suitable shortest path with your constraint.

I came up with this approach that works. It finds both shortest paths, one with the constraint and without the constraint, and returns the preferred result. Not sure this is acceptable for your use case.

call {
    match p=shortestPath((a:Node{id:'A'})-[:REL*..5]-(c:Node{id:'C'}))
    where none(i in nodes(p) where not i.avoid is null and i.avoid=true)
    return p, 1 as rank
    union
    match p=shortestPath((a:Node{id:'A'})-[:REL*..5]-(c:Node{id:'C'}))
    return p, 0 as rank
}
return p
order by rank desc
limit 1

with all nodes:

with missing 'E' node: