文章插图
汉诺塔递归#include <iostream>using namespace std; template<int n> void hanoi(char a, char b, char c){ hanoi<n - 1>(a, c, b); printf("%c -> %c\n", a, c); hanoi<n - 1>(b, a, c);}template<>void hanoi<1>(char a, char b, char c){ printf("%c -> %c\n", a, c);}////////////////////////////////////////////////template<int n, char a, char b, char c> class hanoi1{public: static int hanoi(){ hanoi1<n-1, a, c, b>::hanoi(); printf("%c -> %c\n", a, c); hanoi1<n-1, b, a, c>::hanoi(); }};template<char a, char b, char c>class hanoi1<1, a, b ,c>{public: static int hanoi(){ printf("%c -> %c\n", a, c); }};int main(){ #define N 4 cout<<"类模板偏特化:"; hanoi1<N,'A','B','C'>::hanoi(); cout<<endl; cout<<"函式模板全特化:"; hanoi<3>('A','B','C'); exit(0);}C#using System;class HANOI{ private static int time = 0; static void Main(string[] args) { Hanoi(3, "x", "y", "z"); Console.WriteLine(time + " Times"); Console.ReadKey(); } public static void Hanoi(int n, string x, string y, string z) { if (n == 1) { Console.WriteLine(x + "--->" + z); time++; } else { Hanoi(n - 1, x, z, y); Hanoi(1, x, y, z); Hanoi(n - 1, y, x, z); } }}Javapublic class Hanoi { /** * * @param n 盘子的数目 * @param origin 源座 * @param assist 辅助座 * @param destination 目的座 */ public void hanoi(int n, char origin, char assist, char destination) { if (n == 1) { move(origin, destination); } else { hanoi(n - 1, origin, destination, assist); move(origin, destination); hanoi(n - 1, assist, origin, destination); } } // Print the route of the movement private void move(char origin, char destination) { System.out.println("Direction:" + origin + "--->" + destination); } public static void main(String[] args) { Hanoi hanoi = new Hanoi(); hanoi.hanoi(3, 'A', 'B', 'C'); }}
- 装修材料一览表
- 爱空间装修评价 爱的空间装修公司评论
- 液体食品包装用塑胶複合膜、袋
- 海口东站
- 深圳迪瑞特科技有限公司
- 消费观念
- 空调18度都不冷什么问题
- 开关箱与用电设备水平距离
- 脑叶公司控制部
- Panasonic是什么牌子的空调