Yen's algorithm finds the K shortest simple paths between a source node and a target node. Unlike Dijkstra's shortest path which returns only the single best path, Yen's algorithm returns multiple alternative paths ranked by cost, providing route diversity. This algorithm is commonly used to identify backup paths in case the primary path fails.
The algorithm was proposed by Jin Y. Yen in 1971:
Given a source and target, there may be many paths connecting them. Yen's algorithm finds the top K paths with the lowest cost, where each path contains no repeated nodes.
The algorithm works by:
K paths are found or no more candidates exist.GQLINSERT (A:default {_id: "A"}), (B:default {_id: "B"}), (C:default {_id: "C"}), (D:default {_id: "D"}), (E:default {_id: "E"}), (F:default {_id: "F"}), (G:default {_id: "G"}), (A)-[:default {value: 2}]->(B), (A)-[:default {value: 4}]->(F), (B)-[:default {value: 3}]->(C), (B)-[:default {value: 3}]->(D), (B)-[:default {value: 6}]->(F), (D)-[:default {value: 2}]->(E), (D)-[:default {value: 2}]->(F), (E)-[:default {value: 3}]->(G), (F)-[:default {value: 1}]->(E)
| Name | Type | Default | Description |
|---|---|---|---|
startNode | STRING | / | Required. Source node _id. |
endNode | STRING | / | Required. Target node _id. |
k | INT | 3 | Number of shortest paths to find. |
Returns:
| Column | Type | Description |
|---|---|---|
path | LIST | Ordered list of node _ids in the path |
cost | FLOAT | Total path cost |
rank | INT | Path rank (1 = shortest) |
GQLCALL algo.yens({ startNode: "A", endNode: "G", k: 3 }) YIELD path, cost, rank
Returns the same columns as run mode, streamed for memory efficiency.
GQLCALL algo.yens.stream({ startNode: "A", endNode: "G", k: 3 }) YIELD path, cost, rank RETURN path, cost, rank
Returns:
| Column | Type | Description |
|---|---|---|
pathsFound | INT | Number of shortest paths found |
minCost | FLOAT | Cost of the shortest path |
maxCost | FLOAT | Cost of the longest path among K shortest |
GQLCALL algo.yens.stats({ startNode: "A", endNode: "G", k: 3 }) YIELD pathsFound, minCost, maxCost