天天看點

54. 八皇後問題[eight queens puzzle]

【本文連結】

【題目】

在8×8的國際象棋上擺放八個皇後,使其不能互相攻擊,即任意兩個皇後不得處在同一行、同一列或者同一對角斜線上。下圖中的每個黑色格子表示一個皇後,這就是一種符合條件的擺放方法。請求出總共有多少種擺法。

54. 八皇後問題[eight queens puzzle]

【分析】

之前博文介紹過字元串的全排列,八皇後問題也可以轉換為全排列問題。

由于八個皇後的任意兩個不能處在同一行,那麼每一個皇後占據一行。于是我們可以定義一個數組pos[8],pos[i]=value表示第i行将皇後放置于value位置。先把pos的八個數字分别用0-7初始化,接下來對數組pos數組做全排列。由于我們是用不同的數字初始化數組中的數字,是以任意兩個皇後肯定不同列。我們隻需要判斷得到的每一個排列對應的八個皇後是不是在同一對角斜線上,也就是數組的兩個下标i和j,是不是i-j==pos

[i]- pos [j]或者j-i==pos [i]- pos [j]。

【代碼】

 C++

Code 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

// 54_EightQueensPuzzle.cpp : Defines the entry point for the console application.

//

/*

     version: 1.0

     author: hellogiser

     blog: http://www.cnblogs.com/hellogiser

     date: 2014/5/24

*/

#include "stdafx.h"

#include <iostream>

using namespace std;

#define N 8

int m_nPermutationCount = 0;

int m_nValidCount = 0;

// swap a and b

void Swap(int &a, int &b)

{

    int t = a;

     a = b;

     b = t;

}

// check whether pos array is valid

bool CheckValid(int *pos, int n)

    for (int i = 0; i < n; ++i)

     {

        for (int j = i + 1; j < n; j++)

         {

            //only need to check whether pos[i] and pos[j] are on diagonal

            if (i - j == pos[i] - pos[j] || j - i == pos[i] - pos[j])

             {

                return false;

             }

         }

     }

    return true;

// print pos array

void Print(int *pos, int n)

         printf("%d ", pos[i]);

void Permutation(int *pos, int n, int index)

     m_nPermutationCount++;

    if (index == n)

        // this permutation generated

        if (CheckValid(pos, n))

            // valid permutation

            m_nValidCount++;

            //Print(pos,n);

        }

    else

        for (int i = index; i < n; ++i)

             Swap(pos[index], pos[i]);

             Permutation(pos, n, index + 1);

void EightQueensPuzzle()

    // init pos

    int pos[N];

    for (int i = 0; i < N; i++)

         pos[i] = i;

     Permutation(pos, N, 0);

void test_main()

     EightQueensPuzzle();

     cout << m_nPermutationCount << endl;

     cout << m_nValidCount << endl; //92

int _tmain(int argc, _TCHAR *argv[])

     test_main();

    return 0;

【參考】