递归经典题目

八皇后

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#define rep(i, j, k) for(int i = j; i <= k; i++)
using namespace std;
int a[9], tot = 0; 

void put(int line){
	if(line == 9){
		tot++;
		rep(i, 1, 8){
			rep(j, 1, 8){
				if(a[i] == j)	cout << "*";
				else cout << ' '; 
			}
			cout << endl << endl;
		}
		return;
	}
	rep(i, 1, 8){
		int flag = 1;
		rep(j, 1, line-1){
			if(a[j] == i || abs(i - a[j]) == line - j){
				flag = 0;
			}
		}
		if(flag){
			a[line] = i;
			put(line+1);
		}
	}
}

int main() {
	rep(i, 1, 8){
		a[1] = i;	
	    put(2);
	}
	cout << tot;
    return 0;
}

汉诺塔

#include <iostream>
#include <cstdio>

using namespace std;
 
void hannoi (int n, char A, char B, char C)  // 把A盘里面的圆圈转移到C盘里面【A--C】。
{
    if (n == 1)
    {
        cout << "移动圆圈" << n << "从盘" << A << "盘" << C << endl;  //把最后一个圆环从起点盘移动到目标盘。
    }
    else
    {
        hannoi (n-1, A, C, B);  // 把N-1个圆环从起点盘移动到(当前)没有任何圆环的过度盘;通过B、C盘在此函数调用中调用位置的互换,来实现把N-1个圆环从A盘到B盘的转移【A--B】。
        cout << "移动圆圈" << n << "从盘" << A << "盘" << C << endl;
        hannoi (n-1, B, A, C);  // 把N-1个圆环从国度盘移动到目标盘(模仿1和2的操作方法来实现);通过A、B盘在此函数调用中位置的互换,来实现N-1个圆环从B盘到C盘的转移【B--C】。
    }
}
 
int main()
{
    int n;
    cin >> n;

    hannoi (n, 'a', 'b', 'c');
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值