Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the shortest path with the minimum number of hops in Neo4j?

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.

like image 491
Kimy BF Avatar asked Apr 12 '16 20:04

Kimy BF


People also ask

How do you check if a path is the shortest?

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.

Is the shortest path in a graph unique?

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.

What are the different path finding algorithms?

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.

What is path in algorithm?

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).


1 Answers

@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;
like image 165
cybersam Avatar answered Sep 27 '22 21:09

cybersam