//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。
function hanoi(n, source, auxiliary, target) {
if (n === 1) {
console.log(`Move disk 1 from ${source} to ${target}`);
return;
}
// 移动 n-1 个圆盘从起始杆到辅助杆,借助目标杆
hanoi(n - 1, source, target, auxiliary);
// 移动第 n 个圆盘从起始杆到目标杆
console.log(`Move disk ${n} from ${source} to ${target}`);
// 移动 n-1 个圆盘从辅助杆到目标杆,借助起始杆
hanoi(n - 1, auxiliary, source, target);
}
// 测试
hanoi(3, 'A', 'B', 'C');
console.log('----------------------')
hanoi(4, 'A', 'B', 'C');
console.log('----------------------')
hanoi(5, 'A', 'B', 'C');