雙色河內塔是由之前所介紹過的河內塔規則衍生而來,雙色河內塔的目的是將下圖左上的圓環位置經移動成爲右下的圓環位置:
雙色河內塔或是原始的河內塔,其解法觀念與之前介紹過的河內塔是類似的,同樣也是使用遞回來解,不過這次遞迴解法的目的不同,我們來看雙色的情況,這很簡單,
只要將第一柱的黃色移動至第二柱,而接下來第一柱的藍色移動至第三柱。再來是四個盤的情況,首先必須用遞迴完成下圖左上至右下的移動:
接下來最底層的就不用管它們了,因爲它們已經就定位,只要再處理第一柱的上面兩個盤子就可以了。那麼六個盤的情況呢?一樣!首先必須用遞迴完成下圖左上至右下的移動:
接下來最底層的就不用管它們了,因爲它們已經就定位,只要再處理第一柱上面的四個盤子就可以了,這又與之前只有四盤的情況相同,接下來您就知道該如何進行解題了,無論是八個盤、十個盤以上等,都是用這個觀念來解題。
#include <stdio.h>
void hanoi(int disks, char source, char temp, char target) {
if (disks == 1) {
//disks=表示移動的是兩塊,大小相同,但是顏色不同,一次移動是兩塊
printf("move disk from %c to %c\n", source, target);
printf("move disk from %c to %c\n", source, target);
} else {
hanoi(disks-1, source, target, temp);
hanoi(1, source, temp, target);
hanoi(disks-1, temp, source, target);
}
}
void hanoi2colors(int disks) {
char source = 'A';
char temp = 'B';
char target = 'C';
int i;
for(i = disks / 2; i > 1; i--) {
hanoi(i-1, source, temp, target);//n-1塊移到A=>C
printf("move disk from %c to %c\n", source, temp);//注意A=>B兩次
printf("move disk from %c to %c\n", source, temp);
hanoi(i-1, target, temp, source);//n-1塊從C移回來,C=》A
//以上步驟相仿 單色漢諾塔問題
printf("move disk from %c to %c\n", temp, target);
//最重要的一步來了,到達分離底層的目的 將最大的兩塊分離
}
printf("move disk from %c to %c\n", source, temp);
printf("move disk from %c to %c\n", source, target);
}
int main() {
int n;
printf("請輸入盤數:");
scanf("%d", &n);
hanoi2colors(n);
return 0;
}