pub fn solve_lsap(costs: &[f64], n: usize) -> IgraphResult<Vec<u32>>Expand description
Solve a balanced linear sum assignment problem (Hungarian method).
Given an n×n cost matrix (stored row-major as a flat slice of length n²), find an assignment of each row to exactly one column that minimizes the total cost.
§Arguments
costs— flat row-major n×n cost matrix (length must equaln * n).n— size of the problem (number of rows = number of columns).
§Returns
A vector p of length n where p[i] is the column assigned to row i.
§Errors
Returns an error if costs.len() != n * n, or if n is zero and costs
is non-empty, or if costs contain NaN.
§Examples
use rust_igraph::solve_lsap;
// 3×3 cost matrix:
// [1, 2, 3]
// [2, 4, 6]
// [3, 6, 9]
// Optimal: row 0→col 2 (3), row 1→col 1 (4), row 2→col 0 (3) = 10
// OR: row 0→col 0 (1), row 1→col 1 (4), row 2→col 2 (9) = 14
// Actually optimal: 0→2(3), 1→0(2), 2→1(6) = 11
// Let's use a simpler example:
let costs = vec![
10.0, 5.0, 13.0,
3.0, 7.0, 2.0,
6.0, 8.0, 12.0,
];
let p = solve_lsap(&costs, 3).unwrap();
// Verify it's a valid permutation
let mut used = vec![false; 3];
for &col in &p {
assert!(!used[col as usize]);
used[col as usize] = true;
}