Im modeling a graph where nodes are places and edges indicate that you can go from one place to another.
This is to have all routes that you can take from a place to another, and you can go from a place to another by different routes, so I want a query that returns me the shortest path with the minimum route changes.
For example, I want to go from A to D, I have two possible paths:
(place {name: "A"})-[:FOLLOWS{route:""R1}]->(place{name: "B" })-[:FOLLOWS{route:""R4}]->(place{name:"C"})-[:FOLLOWS{route:""R2}]->(place{name:"D"})
(place {name: "A"})-[:FOLLOWS{route:""R1}]->(place{name: "B" })-[:FOLLOWS{route:""R1}]->(place{name:"F"})-[:FOLLOWS{route:""R2}]->(place{name:"D"})
In the previous two path, both are the same size, but I would like to get the second one, which is the one who has the minimum route changes.
Thank you.
If there are no negative cycles and there is some path from s to t (t is reachable from s), then there is a shortest path from s to t that is simple (it contains no repeated vertices): deletion of a cycle from the path does not increase the length of the path.
Shortest paths are normally simple. Our algorithms ignore zero-weight edges that form cycles, so that the shortest paths they find have no cycles. Shortest paths are not necessarily unique. There may be multiple paths of the lowest weight from one vertex to another; we are content to find any one of them.
Specifically, the pathfinding algorithms we'll cover are: Shortest Path, with two useful variations (A* and Yen's) Finding the shortest path or paths between two chosen nodes. All Pairs Shortest Path and Single Source Shortest Path.
In graph theory, a path in a graph is a finite or infinite sequence of edges which joins a sequence of vertices which, by most definitions, are all distinct (and since the vertices are distinct, so are the edges).
@DevBennett's answer gets the shortest path with the minimum number of route changes.
To get the shortest path with the minimum number of different routes, which is what the question literally asked for (but which may not have been what the asker actually wanted), you can use this query:
MATCH p=ALLSHORTESTPATHS((a:Place {name: "A"})-[:FOLLOWS*]->(d:Place{name:"D"}))
UNWIND RELATIONSHIPS(p) AS rel
WITH p, COUNT(DISTINCT rel.route) AS nRoutes
RETURN p, nRoutes
ORDER BY nRoutes
LIMIT 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With