| k_shortest_paths | R Documentation |
Computes up to k shortest loopless paths between two nodes using
Yen's algorithm. Each path is a sequence of distinct nodes from source to
target.
k_shortest_paths(x, from, to, k = 3, weights = NULL, directed = NULL, ...)
x |
Network input: matrix, igraph, network, cograph_network, or tna object |
from |
Character or numeric node identifier for the source node. |
to |
Character or numeric node identifier for the target node. |
k |
Integer; number of shortest paths to find. Default 3. |
weights |
Edge weight handling: NULL (default) auto-detects from edge attributes, NA forces unweighted distances, or a numeric vector of custom weights. |
directed |
Logical or NULL. If NULL (default), auto-detect from matrix symmetry. Set TRUE to force directed, FALSE to force undirected. |
... |
Additional arguments passed to |
Yen's algorithm finds the k shortest loopless (simple) paths in a graph. It works by:
Finding the shortest path via Dijkstra's algorithm
For each subsequent path, systematically exploring deviations from previously found paths by temporarily removing edges, finding spur paths, and selecting the shortest candidate
The algorithm may return fewer than k paths if fewer distinct loopless
paths exist between the two nodes.
A list with class "cograph_k_paths" containing:
List of up to k character vectors, each containing node
names in path order
Numeric vector of path lengths (sum of edge weights or hop count)
Source node name
Target node name
Number of paths requested
Yen, J.Y. (1971). Finding the K shortest loopless paths in a network. Management Science, 17(11), 712-716. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.1287/mnsc.17.11.712")}
shortest_paths
# Find 3 shortest paths in a small network
adj <- matrix(c(
0, 1, 1, 0, 0,
0, 0, 1, 1, 0,
0, 0, 0, 1, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 0
), 5, 5, byrow = TRUE)
rownames(adj) <- colnames(adj) <- LETTERS[1:5]
kp <- cograph::k_shortest_paths(adj, from = "A", to = "E", k = 3)
kp
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.