问题背景:在 8×8 格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,输出所有摆法。
环境:VS2017
代码:
#include "pch.h"
#include <iostream>
#include <cstdio>
#include <sys/timeb.h>
using namespace std;
const int MAX_SIZE = 100;
enum flag { blank = '+', queen = 'O' };
char Chess[MAX_SIZE][MAX_SIZE]; //棋盘
int n; //解决n皇后问题
int total;
//对棋盘进行初始化
void Init()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
Chess[i][j] = blank;
total = 0;
}
//判断(r,c)位置是否可放置
bool Judge(int r, int c)
{
int i, j;
for (i = r + 1; i < n; i++)
if (Chess[i][c] == queen)
return false; //说明c列上已有一皇后
for (i = c + 1; i < n; i++)
if (Chess[r][i] == queen)
return false; //说明r行上已有一皇后
for (i = r + 1, j = c + 1; (i < n) && (j < n); i++, j++)
if (Chess[i][j] == queen)
return false; //对角线上已有一皇后
for (i = r + 1, j = c - 1; (i < n) && (j >= 0); i++, j--)
if (Chess[i][j] == queen)
return false; //对角线上已有一皇后
return true;
}
//递归算法主程序
void Backtrack(int k, int cnt)
{
if (k < 0 || cnt == n)
{
if (cnt == n)
{
printf("No.%d:\n", ++total);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
printf(" %c ", Chess[i][j]);
putchar('\n');
}
putchar('\n');
}
}
else
{
int r = k / n, c = k % n;
if (Judge(r, c))
{
Chess[r][c] = queen;
Backtrack(k - 1, cnt + 1);
Chess[r][c] = blank;
}
Backtrack(k - 1, cnt);
}
}
int main()
{
timeb t1, t2;
long kk;
cout << "输入皇后个数:";
while (cin >> n)
{
Init();
ftime(&t1);
Backtrack(n*n - 1, 0);
ftime(&t2);
cout << "计算" << n << "皇后问题总共可有" << total << "种摆法!" << endl;
kk = (t2.time - t1.time) * 1000 + t2.millitm - t1.millitm;
cout << "本次递归耗时:" << kk << "毫秒" << endl;
system("PAUSE");
cout << "输入皇后个数:";
}
return 0;
}
结果: