您的位置:首页 > 职场人生

剑指Offer----面试题28----扩展:八皇后问题

2016-06-06 22:55 369 查看

题目:

在8×8的国际象棋上摆放八个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。下图中的每个黑色格子表示一个皇后,这就是一种符合条件的摆放方法。请求出总共有多少种摆法?



分析:

由于八个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。于是我们可以定义一个数组ColumnIndex[8],数组中第i个数字表示位于第i行的皇后的列号。先把ColumnIndex的八个数字分别用0-7初始化,接下来我们要做的事情就是对数组ColumnIndex做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的八个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==ColumnIndex[i]-Column[j]或者j-i==ColumnIndex[i]-ColumnIndex[j]。

源代码如下:

#include<iostream>
using namespace std;

int g_number = 0;
void Permutation(int *, int, int);
void Print(int *, int);

void EightQueen()
{
const int queens = 8;//八皇后问题
int ColumnIndex[queens];
for (int i = 0; i < queens; ++i)
ColumnIndex[i] = i;    //初始化
Permutation(ColumnIndex, queens, 0);
}

bool Check(int ColumnIndex[], int length)
{
int i, j;
for (i = 0; i < length; ++i)
{
for (j = i + 1; j < length; ++j)
{
if (i - j == ColumnIndex[i] - ColumnIndex[j] || j - i == ColumnIndex[i] - ColumnIndex[j])   //在正、副对角线上
return false;
}
}
return true;
}
void Permutation(int ColumnIndex[], int length, int index)
{
if (index == length)
{
if (Check(ColumnIndex, length))   //检测棋盘当前的状态是否合法
{
++g_number;
Print(ColumnIndex, length);
}
}
else
{
for (int i = index; i < length; ++i)   //全排列
{
swap(ColumnIndex[index], ColumnIndex[i]);
Permutation(ColumnIndex, length, index + 1);
swap(ColumnIndex[index], ColumnIndex[i]);
}
}
}

void Print(int ColumnIndex[], int length)
{
printf("%d\n", g_number);
for (int i = 0; i < length; ++i)
printf("%d ", ColumnIndex[i]);
printf("\n");
}

int main(void)
{
E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 2 6 1 3
57
4 6 3 0 2 7 5 1
58
4 6 0 3 1 7 5 2
59
4 6 0 2 7 5 3 1
60
4 6 1 3 7 0 2 5
61
4 6 1 5 2 0 3 7
62
4 6 1 5 2 0 7 3
63
4 7 3 0 2 5 1 6
64
4 7 3 0 6 1 5 2
65
5 1 6 0 3 7 4 2
66
5 1 6 0 2 4 7 3
67
5 2 4 6 0 3 1 7
68
5 2 4 7 0 3 1 6
69
5 2 0 6 4 7 1 3
70
5 2 0 7 4 1 3 6
71
5 2 0 7 3 1 6 4
72
5 2 6 3 0 7 1 4
73
5 2 6 1 3 7 0 4
74
5 2 6 1 7 4 0 3
75
5 3 1 7 4 6 0 2
76
5 3 0 4 7 1 6 2
77
5 3 6 0 2 4 1 7
78
5 3 6 0 7 1 4 2
79
5 0 4 1 7 2 6 3
80
5 7 1 3 0 6 4 2
81
6 1 3 0 7 4 2 5
82
6 1 5 2 0 3 7 4
83
6 2 0 5 7 4 1 3
84
6 2 7 1 4 0 5 3
85
6 3 1 4 7 0 2 5
86
6 3 1 7 5 0 2 4
87
6 4 2 0 5 7 1 3
88
6 0 2 7 5 3 1 4
89
7 1 3 0 6 4 2 5
90
7 1 4 2 0 6 3 5
91
7 2 0 5 1 4 6 3
92
7 3 0 2 5 1 6 4
请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息