← 输入框|github.com|刷新
Skip to content

第 25 期(算法-递归):汉诺塔(河内塔) #28

Open

Description

@wingmeng

题目:

汉诺塔是一个益智游戏,塔的设备包括三根柱子和一套直径不一的空心圆盘。开始时源柱子上的所有圆盘都按照较小的圆盘放在较大的圆盘之上的顺序堆叠。目标是通过每次移动一个圆盘到另一根柱子上,最终将一堆圆盘移动到目标柱子上,过程中不可将大的圆盘放置在较小的圆盘之上。

image

请使用 js 编写汉诺塔算法。(在浏览器控制台输出解法)

/**
 * @param {number} n - 圆盘数量
 * @param {string} A - 源柱子名称
 * @param {string} B - 辅助柱子名称
 * @param {string} C - 目标柱子名称
 */
function hanoi(n, A, B, C) {
  // 你的代码
}

测试用例:

hanoi(3, 'A', 'B', 'C');

// 控制台输出:
/*
  Move disc 1 from A to C
  Move disc 2 from A to B
  Move disc 1 from C to B
  Move disc 3 from A to C
  Move disc 1 from B to A
  Move disc 2 from B to C
  Move disc 1 from A to C
*/

参考答案:

function hanoi(n, A, B, C) {
  if (n > 0) {
    hanoi(n - 1, A, C, B);
    console.log(`Move disc ${n} from ${A} to ${C}`);
    hanoi(n - 1, B, A, C);
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions