-
Notifications
You must be signed in to change notification settings - Fork 0
/
nqueen.cpp
101 lines (85 loc) · 1.66 KB
/
nqueen.cpp
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
96
97
98
99
100
101
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
void print( int arr[][50], int n );
void place_queen( int row, int arr[][50], int n );
int main()
{
int n;
cin >> n;
while ( n != EOF ) {
int arr[n][50];
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ ) {
arr[i][j] = 0;
}
}
for ( int i = 0; i < n; i++ ) {
int k;
cin >> k;
if ( k > 0 ) {
arr[i][k - 1] = 2;
}
}
for ( int i = 0; i < n; i++ ) {
place_queen(i, arr, n );
}
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ ) {
if ( arr[i][j] == 1 || arr[i][j] == 2 ) {
cout << j + 1 << " ";
}
}
}
cout << endl;
cin >> n;
}
return 0;
}
void place_queen( int row, int arr[][50], int n ) {
int q_present = 0;
for ( int i = 0; i < n; i++ ) {
if ( arr[row][i] == 1 ) {
arr[row][i] = 0;
if ( i == n - 1 ) {
place_queen(row - 1, arr, n);
place_queen(row, arr, n);
return;
}
q_present = i + 1;
}
if ( arr[row][i] == 2 ) {
place_queen(row - 1, arr, n);
return;
}
}
for ( int col = q_present; col < n; col++ ) {
int q_c = 0;
for ( int j = 0; j < n; j++ ) {
for ( int k = 0; k < n; k++ ) {
if ( j == row || k == col || j + k == col + row || j - k == row - col ) {
if ( arr[j][k] == 1 || arr[j][k] == 2 ) {
q_c++;
break;
}
}
}
}
if ( q_c == 0 ) {
arr[row][col] = 1;
return;
}
}
place_queen(row - 1, arr, n);
place_queen(row, arr, n);
}
void print( int arr[][50], int n ) {
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ ) {
cout << arr[i][j];
}
cout << endl;
}
cout << endl << endl;
}