汉诺塔算法

  1. pub fn hanoi(n: i32, from: i32, to: i32, via: i32, moves: &mut Vec<(i32, i32)>) {
  2. if n > 0 {
  3. hanoi(n - 1, from, via, to, moves);
  4. moves.push((from, to));
  5. hanoi(n - 1, via, to, from, moves);
  6. }
  7. }
  8. #[cfg(test)]
  9. mod tests {
  10. use super::*;
  11. #[test]
  12. fn hanoi_simple() {
  13. let correct_solution: Vec<(i32, i32)> =
  14. vec![(1, 3), (1, 2), (3, 2), (1, 3), (2, 1), (2, 3), (1, 3)];
  15. let mut our_solution: Vec<(i32, i32)> = Vec::new();
  16. hanoi(3, 1, 3, 2, &mut our_solution);
  17. assert_eq!(correct_solution, our_solution);
  18. }
  19. }