# 算法之路（四）----汉诺塔（又称河内之塔）

• 1 每次只能移动一个圆盘；
• 2 大盘不能叠在小盘上面。

3个圆盘的汉诺塔移动

4个圆盘的汉诺塔移动

## 递归解

```- (void)viewDidLoad {
int n = 9;
[self hannoi:n from:@"A" buffer:@"B" to:@"C"];
NSLog(@"一共 %d 步",count);
}

- (void)hannoi:(int)n from:(NSString *)from buffer:(NSString *)buffer to:(NSString *)to
{
if (n == 1) {
NSLog(@"Move disk %d from %@ to %@", n, from, to);
} else {
[self hannoi:n-1 from:from buffer:to to:buffer];
NSLog(@"Move disk %d from %@ to %@", n, from, to);
[self hannoi:n-1 from:buffer buffer:from to:to];
}
}

console : 一共 511 步```

```using namespace std;
#include <iostream>
#include <cstdio>

void hannoi (int n, char from, char buffer, char to)
{
if (n == 1) {
cout << "Move disk " << n << " from " << from << " to " << to << endl;
} else {
hannoi (n-1, from, to, buffer);
cout << "Move disk " << n << " from " << from << " to " << to << endl;
hannoi (n-1, buffer, from, to);
}
}

int main()
{
int n;
cin >> n;
hannoi (n, 'A', 'B', 'C');
return 0;
}```

70 篇文章16 人订阅

0 条评论

## 相关文章

8210

28040

### SQL中GROUP BY用法示例

GROUP BY我们可以先从字面上来理解，GROUP表示分组，BY后面写字段名，就表示根据哪个字段进行分组，如果有用Excel比较多的话，GROUP BY比较类...

5.1K20

19090

21870

31340

17830

19140

13740

14710