Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Jun 3, 2019 · 0 comments
Open

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

wingmeng opened this issue Jun 3, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 3, 2019

题目:

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

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);
  }
}
@wingmeng wingmeng closed this as completed Jun 4, 2019
@wingmeng wingmeng reopened this Jun 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant