本文主要是介绍汉诺塔实现(含数组修改)Implement of hanoi,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
汉诺塔的实现,包含伪代码,以及输出流程版本和修改数组版本。
#include <iostream>
using namespace std;void hanoiPseudocode(int n, char A, char B, char C)
{如果是一个盘子直接将盘子从A移到C;否则将 n-1个盘子借助C移到B;直接将盘子从A移到C;将B上的n-1个盘子借助A移到C;}
void hanoi(int n, char x, char y, char z)
{if(n == 1)cout << "move " << n << " from " << x << " to " << z << "\n";else{hanoi(n-1,x,z,y);cout << "move " << n << " from " << x << " to " << z << "\n";hanoi(n-1,y,x,z);}
}void Move(int size,int *x, int *z)
{int i = 0, j = 0;while (x[i]!=-1 && i < size) i++;while (z[j]!=-1 && j < size) j++;z[j] = x[i-1];x[i-1] = -1;for (int i = 0; i < size; i++){cout << x[i] << " ";}cout << "\n";for (int i = 0; i < size; i++){cout << z[i] << " ";}cout << "\n";
}
void HanoiMove(int n, int size, int *x, int *y, int *z)
{if(n == 1)Move(size,x,z);else{HanoiMove(n-1,size,x,z,y);Move(size,x,z);HanoiMove(n-1,size,y,x,z);}
}
int main()
{int n = 3;hanoi(n,'A','B','C');int a[] = {3,2,1};int b[3] = {-1,-1,-1};int c[3] = {-1,-1,-1};HanoiMove(n,n,a,b,c);for (int i = 0; i < n; i++){cout << a[i] << " ";}cout << "\n";for (int i = 0; i < n; i++){cout << b[i] << " ";}cout << "\n";for (int i = 0; i < n; i++){cout << c[i] << " ";}cout << "\n";return 0;
}
这篇关于汉诺塔实现(含数组修改)Implement of hanoi的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!