4.7. 图算法范例
提示
范例源代码下载地址: PathFindingExamplesTest.java计算正连个节点之间的最短路径(最少数目的关系):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Node startNode = graphDb.createNode(); Node middleNode1 = graphDb.createNode(); Node middleNode2 = graphDb.createNode(); Node middleNode3 = graphDb.createNode(); Node endNode = graphDb.createNode(); createRelationshipsBetween( startNode, middleNode1, endNode ); createRelationshipsBetween( startNode, middleNode2, middleNode3, endNode ); // Will find the shortest path between startNode and endNode via // "MY_TYPE" relationships (in OUTGOING direction), like f.ex: // // (startNode)-->(middleNode1)-->(endNode) // PathFinder<Path> finder = GraphAlgoFactory.shortestPath( Traversal.expanderForTypes( ExampleTypes.MY_TYPE, Direction.OUTGOING ), 15 ); Iterable<Path> paths = finder.findAllPaths( startNode, endNode );使用 迪科斯彻(Dijkstra) 算法解决有向图中任意两个顶点之间的最短路径问题。
1 2 3 4 5 6 7 PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra( Traversal.expanderForTypes( ExampleTypes.MY_TYPE, Direction.BOTH ), "cost" ); WeightedPath path = finder.findSinglePath( nodeA, nodeB ); // Get the weight for the found path path.weight();使用 A* 算法是解决静态路网中求解最短路最有效的方法。
这儿是我们的范例图: