四根柱子的汉诺塔,求最小移动次数

#include
#include 
using namespace std;

//level: 当前要移动的汉诺塔是第level层,最上一层为第一层 
int move(int level, char start, char end){
	//printf("[%d] %c -> %c\n",level, start, end);
	return 1;
}


int hanio_3(int n, char a, char b, char c){
	if(n == 1) return 1;
	int x1 = hanio_3(n - 1, a, c, b);
	int x2 = move(n, a, c);
	int x3 = hanio_3(n - 1, b, a, c);
	return x1 + x2 + x3;
}

int hanio_4(int n, char a, char b, char c, char d){
	if(n == 1) return 1;
	int minNum = 0x7fffffff;
	for(int i = 1; i < n; i++){
		int x1 = hanio_4(i, a, c, d, b);
		int x2 = hanio_3(n-i, a, c, d);
		int x3 = hanio_4(i, b, c, a, d);
		minNum = min(minNum,x1+x2+x3);
	}
	return minNum;
}

int main(){
	for(int i =1; i <= 12; i++){
		int x = hanio_4(i, 'A', 'B', 'C', 'D');
		cout << "层数为:" << i << ",  最小移动次数:" << x <<  endl;	
	}		
	return 0;
} 

你可能感兴趣的:(算法)