-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nqueen.cc
77 lines (61 loc) · 1.95 KB
/
Nqueen.cc
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
#include<iostream>
#include<cmath>
using namespace std ;
class queen
{
public :
queen (){};
//queen(int row = -1, int col = -1) : m_row(row), m_col(col) {}
void setRow( int row) { m_row = row ; }
void setCol( int col) { m_col = col ; }
int getCol() const {return m_col ; }
int getRow() const {return m_row ; }
private :
int m_row;
int m_col;
};
// curr : 当前的皇后序号(第几个皇后),该值也表明该皇后在第几行
void Queue( queen * nq , int curr , int *sum , int n )
{
if ( curr == n )
{
for (int i = 0 ; i < n ; i ++)
{
cout << nq [i ]. getCol()<< " " ;
}
cout <<endl ;
(* sum )++;
return ;
}
int i, j;
for ( i = 0 ; i < n; i++) // i 表示所有列,依次尝试放在每一列
{
for ( j = 0 ; j < curr; j++) // j 代表已经放下的皇后
{
//if( abs(nq[j].getCol() - nq[i].getCol()) == abs(nq[j].getRow() - nq[i].getRow()) || nq[i].getCol() == nq[j].getCol())
if ( abs (nq [j ]. getCol() - i) == abs (nq [j ].getRow () - curr ) || nq [j ].getCol () == i)
break ;
}
if ( j == curr ) // 可以放下,和前 curr - 1 个皇后都不冲突
{
nq[ curr ].setCol (i );
Queue (nq , curr + 1 , sum , n );
}
}
}
int nqueenP( int n)
{
queen * nq = new queen [n ];
for (int i = 0 ; i < n ; i ++)
{
nq[ i]. setRow (i );
nq[ i]. setCol (0 );
}
int sum = 0 ;
Queue (nq ,0 ,&sum ,n );
return sum ;
}
int main()
{
cout <<"8 Queue Result: " << nqueenP( 8 )<<endl ;
}